开发者

Whats the standard way to manage many to many relationships using checkboxes on rails these days?

开发者 https://www.devze.com 2023-02-24 08:36 出处:网络
Forgive me if this is a silly question bec开发者_如何学Pythonause i\'m still fairly new to rails,

Forgive me if this is a silly question bec开发者_如何学Pythonause i'm still fairly new to rails,

Whats the standard way to manage many to many relationships using checkboxes on rails these days?

Anything ive seen requires either patching with method_missing or using a after_save callback..

Is there an automatic way of doing it in rails 3?

(Using a relationship model and not HABTM)

Thanks

Daniel


I believe a has_many through is what you want, as HABTM is deprecated from what I understand.

For example, I have Devise implemented into my project with users, and users can have many roles, roles has many users. There is a table called "assignments" (with user_id and role_id columns) that links the users and roles tables.

So my models look something like...

user.rb

has_many :assignments, :dependent => :destroy
has_many :roles, :through => :assignments

assignment.rb

belongs_to :user
belongs_to :role

role.rb

has_many :assignments  
has_many :users, :through => :assignments

Then in my view _form.html.erb for Users, I have

<% for role in Role.find(:all) %>
  <%= check_box_tag "user[role_ids][]", role.id, @user.roles.include?(role), :multiple => true, :include_blank => TRUE %>
  <%= role.name %>
<% end %>

So when the user is saved with the appropriate checkboxes, the relationships are taken care of. Anyway, I don't recall the episode number, but there is a Railscast that I believe I got this from.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号