In my controller I would like to do the following:
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 return an ActiveRecord::Associations::CollectionProxy like this for exemple:
=> #<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">]>
When clicking the f.submit in my form, it triggers the push_sub action which pushes a new @sub to the association of the selected item (@food).
I do not know how to get the ID of the selected Food in my form so that I can use it in my controller.
Here is my form:
<%= 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 %>
Thank you very much in advance for your help.
Happy new year to you all !
Antoine
UPDATE
I have 3 models with a has_many through relationship: Food (eg: Chocolate), Sub (Chocolate food substitute), Joint (joint table).
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