Ruby on rails 多选下拉列表公司并保存特权和相应公司

Ruby on rails 多选下拉列表公司并保存特权和相应公司,ruby-on-rails,ruby,Ruby On Rails,Ruby,这是我的密码: 当多个真/假时,在多个选择上不保存特权。perk save和habtm正在工作 class Perk < ActiveRecord::Base has_and_belongs_to_many :companies end class Company < ActiveRecord::Base has_and_belongs_to_many :perks end class Perkparams[:Company\u id]) @perk听起来您可能没有在控制器的p

这是我的密码:

多个真/假
时,在
多个选择
上不保存特权。perk save和habtm正在工作

class Perk < ActiveRecord::Base
 has_and_belongs_to_many :companies
end
class Company < ActiveRecord::Base
 has_and_belongs_to_many :perks
end
class Perk
查看perk/new.html.erb

<%= select_tag "company_id", options_from_collection_for_select(Company.all, 'id', 'name',@perk.companies.map{ |j| j.id }), :multiple => true %>
<%= f.text_field :name  %>
true%>
控制器代码:

def new
  @perk = Perk.new
  respond_with(@perk)
end

def create
  @perk = Perk.new(perk_params)
  @companies = Company.where(:id => params[:company_id])
  @perk << @companies 
  respond_with(@perk)
end
def新建
@额外津贴
以(@perk)回应
结束
def创建
@额外津贴=额外津贴新(额外津贴参数)
@companys=公司。其中(:id=>params[:Company\u id])

@perk听起来您可能没有在控制器的perk_params方法中包含company_id。Rails 4使用了强pramas,这意味着您需要声明允许设置的参数。但是,如果没有看到更多的代码,就很难确定

在您的控制器中,您应该看到这样一个方法(可能有更多选项,只有:name):

您应该尝试向其添加:company\u id,使其看起来像这样:

def perk_params
  params.require(:perk).permit(:name, :company_id)
end
如果方法中还有其他参数,请保留它们,并添加:company_id

编辑到原始答案

以上仅适用于一对多或一对一,因为您使用的是has_和_属于_,您需要将公司:[]添加到参数列表的末尾,如下所示

def perk_params
  params.require(:perk).permit(:name, companies: [] )
end
def perk_params
  params.require(:perk).permit(:name, companies_ids: [] )
end
还是像这样

def perk_params
  params.require(:perk).permit(:name, companies: [] )
end
def perk_params
  params.require(:perk).permit(:name, companies_ids: [] )
end
有关更多详细信息,请参阅以下链接:


您的
选择标记应返回一个公司ID数组:

<%= select_tag "company_ids[]", options_from_collection_for_select(Company.all, 'id', 'name',@perk.companies.map{ |j| j.id }), :multiple => true %>

(我假设您在创建操作中故意省略了
@perk.save
调用……否则,也应该包括在内。
Model.new
不存储记录。)

如果您的问题更清楚,您将有更好的机会获得好的答案,这表明您所做的一些研究,你尝试了什么,犯了什么错误,等等。一定要阅读并确认。谢谢@mark。我已经允许公司id进入perks params。但它仍然不起作用。对不起,我刚刚重新阅读了你的问题“公司id是一对多还是一对一关系”。因为您使用的是has_和_-belish_-to_-many,所以需要在perk_-params方法中的lis参数末尾添加公司:[]