如何在表单中创建多对多关联的复选框

时间:2014-02-12 05:11:01

标签: ruby-on-rails forms ruby-on-rails-4

我有很多关联,并且对如何创建复选框感到困惑。

型号:lodge.rb

    has_many :lodge_facilities, :dependent => :destroy
    has_many :facilities, through: :lodge_facilities, :dependent => :destroy    
    accepts_nested_attributes_for :facilities  

型号:lodge_facility.rb

belongs_to :lodge
belongs_to :facility

model:facility.rb

    has_many :lodge_facilities, :dependent => :destroy
has_many :facilities, through: :lodge_facilities, :dependent => :destroy

以我的形式尝试

<%= form_for @lodge, :class =>'lodge_form', url: admins_lodge_path, method: :put,:html => {:multipart => true} do |f|%>
<%= f.fields_for :lodge_facilities do |fac| %>
    <%= fac.check_box :ac %>
    <%= fac.label :ac,'AC' %>
    <%= fac.check_box :wifi %>
    <%= fac.label :ac,'Wifi' %>
<% end %>

这会显示复选框,但是当我在控制台中提交表单时,我会看到Unpermitted parameters: lodge_facilities 在我的控制器中,我添加了

def lodge_params     
 params.require(:lodge).permit(lodge_facilities_attributes:[:id,:lodge_id,:lodge_facility_id],facilities_attributes: [:id,:ac,:wifi,:internet,:bar,:restaurant,:gym,:pool,:laundry,:parking,:transportation] )
      end

我缺少什么?

1 个答案:

答案 0 :(得分:0)

试试这个:

    def lodge_params     
 params.require(:lodge).permit(lodge_facilities_attributes:[:id,:lodge_id,:lodge_facility_id],lodge_facilities: [:id,:ac,:wifi,:internet,:bar,:restaurant,:gym,:pool,:laundry,:parking,:transportation] )
      end

你也可以使用nested_form gem

https://github.com/ryanb/nested_form