在我的控制器中,我想执行以下操作:
class SubsController < ApplicationController
def push_sub
@sub = Sub.find(params[:id])
@food = Food.find("ID of food selected from collection_select") => see my form down below
@food.subs << @sub
end
private
def sub_params
params.require(:sub).permit(:name, :description)
end
end
@ food.subs返回一个ActiveRecord :: Associations :: CollectionProxy,例如:
=> #<ActiveRecord::Associations::CollectionProxy [#<Sub id: 34, name: "Fake choco", description: "cacao fake", created_at: "2015-01-07 23:40:25", updated_at: "2015-01-07 23:40:25">, #<Sub id: 34, name: "Fake choco", description: "cacao fake", created_at: "2015-01-07 23:40:25", updated_at: "2015-01-07 23:40:25">, #<Sub id: 34, name: "Fake choco", description: "cacao fake", created_at: "2015-01-07 23:40:25", updated_at: "2015-01-07 23:40:25">]>
当单击表单中的f.submit时,它会触发push_sub操作,该操作会将新的@sub推送到所选项目的关联(@food)。
我不知道如何在我的表单中获取所选食物的ID,以便我可以在我的控制器中使用它。
这是我的表格:
<%= form_for @sub, :url => {:action => "push_sub"} do |f| %>
<h1>What food is <%="#{@sub.name}"%> a substitute of?</h1>
<div class="field">
<%=collection_select(:sub, :foods, Food.all, :id, :name)%>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
非常感谢您的帮助。
祝你们大家新年快乐!安托
我有3个带有has_many关系的模型:食物(例如:巧克力),Sub(巧克力食物替代品),关节(联合表)。
class Food < ActiveRecord::Base
has_many :joints
has_many :subs, :through => :joints
accepts_nested_attributes_for :subs, reject_if: :all_blank, allow_destroy: true
end
class Sub < ActiveRecord::Base
has_many :joints
has_many :foods, :through => :joints
accepts_nested_attributes_for :foods, reject_if: :all_blank, allow_destroy: true
end
class Joint < ActiveRecord::Base
belongs_to :food
belongs_to :sub
end
答案 0 :(得分:0)
我找到了答案:
我可以像我这样迭代控制器中的参数:
params[:sub].each do |k, v|
@food_id = v
end
所以我可以使用@food_id将Sub推送到其活动记录集合代理。