How to use Many to Many in Rails?

Posted by Newbie on Stack Overflow See other posts from Stack Overflow or by Newbie
Published on 2010-06-02T11:20:15Z Indexed on 2010/06/02 11:23 UTC
Read the original article Hit count: 171

Filed under:
|

Hello! In my project, I have users and quests. One User can join multiple quests and one quest can have multiple users. So I created a table called questing, containing the user_id and the quest_id. In my user.rb I did following:

require 'digest/sha1'
class User < ActiveRecord::Base
  has_many :questings
  has_many :quests ,:through =>:questings
  ...

My Quest.rb:

class Quest < ActiveRecord::Base
  has_many :questings
  has_many :users ,:through =>:questings
  ...

My Questing.rb:

class Questing < ActiveRecord::Base
  belongs_to :quest
  belongs_to :user
end

Now I want to create a link or button on my /quests/show.html.erb, calling an action in my controller, which will create the relationship between user and quest.

So, in my quest_controller I did:

  def join_quest
    @quest = Quest.find(params[:id])
    puts '************************'
    puts 'join quest:' + @quest.id
    puts '************************'
    respond_to do |format|
      format.html { redirect_to(@quest) }
      format.xml  { head :ok }
    end
  end

and in my show.html.erb I did:

<%= link_to 'join this quest!!!', :action => :join_quest %>

Now, clicking on this link will cause an error like: Couldn't find Quest with ID=join_quest and the url points to */quests/join_quest* instead of */quests/1/join_quest*

Now my questions:

Is my quests_controller the right place for my join_quest action, or should I move it to my users_controller?

Why do I get this error? How to solve it?

What do I have to write in my join_quest action for saving the relationship?

On my /users/show.html.erb I want to output all quests the user joined. How to do this? I have to get all this quests from my relationship table, right? How?

I hope you can help me! THX!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about many-to-many