0
在我的member_profile表單中,我希望角色複選框對管理員可見。我想使用一些嵌套的form_for,但無法使其工作,所以我採取手動創建check_box_tags(見下文),然後手動將它們添加到member_profile.member。如何使用form_for更新關聯的has_many:關聯
請注意,成員模型是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
表(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
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
什麼不工作?就像你無法獲得表格來顯示關聯一樣?他們不會保存提交?請詳細說明發生了什麼問題。 – pjammer 2011-03-15 18:25:03