[英]How can I use form_for to update an association's has_many :through association
In my form for member_profile, I would like to have role checkboxes that are visible for admins. 在我的member_profile表单中,我希望有一个管理员可见的角色复选框。 I would like to used some nested form_for, but can't make it work, so I've resorted to manually creating the check_box_tags (see below), and then manually adding them to member_profile.member.
我想使用一些嵌套的form_for,但无法使其正常工作,因此我不得不手动创建check_box_tags(请参见下文),然后将其手动添加到member_profile.member。
Note that the Member model is Devise, and I don't want to mix those fields in with my MemberProfile data, in case I change auth systems in the future. 请注意,成员模型是Devise,并且我不想在我的MemberProfile数据中混入这些字段,以防将来将来更改身份验证系统。
class Member < ActiveRecord::Base
has_one :member_profile
has_many :member_roles
has_many :roles, :through => :member_roles
end
class MemberProfile < ActiveRecord::Base
belongs_to :member
has_many :member_roles, :through => :member
#has_many :roles, :through => :member_roles #can't make this work work
end
class Role < ActiveRecord::Base
has_many :member_roles
validates_presence_of :name
end
class MemberRole < ActiveRecord::Base
belongs_to :member
belongs_to :role
end
Form (haml) 形式(哈姆尔)
= form_section do
- Role.all.each do |x|
=check_box_tag 'member[role_ids][]',
x.id,
begin @resource.member.role_ids.include?(x.id) rescue nil end
=x.name
member_profiles_controller.rb member_profiles_controller.rb
def update
if @resource.update_attributes params[:member_profile]
@resource.member.role_ids = params[:member][:role_ids]
redirect_to(@resource, :notice => 'Member profile was successfully updated.')
else
render :action => "edit"
end
end
I've decided it only makes sense to do a nested has_many :through on Update, since the join model is what is being 'gone through' to get to the has_many :through model. 我已经决定在Update上执行嵌套的has_many:through是唯一有意义的,因为join模型是“ gone through”到达has_many:through模型的原因。 Before the hmt is created, there is obviously no record in the join model.
在创建hmt之前,联接模型中显然没有任何记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.