As you may (or may not) know, there are two ways to build a many-to-many (or N-N) relationship with Rails.
- The first way uses has_and_belongs_to_many in both models. You’ll have to create a join table that has no corresponding model or primary key. ( ActiveRecord will look by default for a join table called groups_users )
- The second way uses a has_many association with the :through option and a join model:
class Subscriptions < ActiveRecord::Base
belongs_to :group # foreign key - programmer_id
belongs_to :user # foreign key - project_id
end
class Group :subscriptions
end
class User :subscriptions
end
class Group < ActiveRecord::Base
has_and_belongs_to_many :users # foreign keys in the join table
end
class User < ActiveRecord::Base
has_and_belongs_to_many :groups # foreign keys in the join table
end
The join table can have more attributes which can be filled with the push_with_attributes method:
class User < ActiveRecord::Base
has_and_belongs_to_many :groups # foreign keys in the join table
def join_group(group)
groups.push_with_attributes(group, :joined_at => Time.now)
end
end
If you have to work with the relationship model as its own entity, thent you'll need to use has_many :through. Otherwise, you can just stick to has_and_belongs_to_many.
Hell this post is unreadable.
WTF! can a human read this?
The display is unreadable because the poster didn’t put the code in a pre format block (could be a code tag or pre tag). As a result, the display ignores new line and the code part messes up the whole readability.
Anyway, the post is not that helpful to me. What I am really looking for is a way to use and some examples of how to use in model, controller, and view. This post just shows how to use in model…
The display is unreadable because the poster didn’t put the code in a pre format block (could be a code tag or pre tag). As a result, the display ignores new line and the code part messes up the whole readability.
Anyway, the post is not that helpful to me. What I am really looking for is a way to use and some examples of how to use in model, controller, and view. This post just shows how to use in model…