我做了一個演示給你:http://meals-test2.herokuapp.com/new 
- 如果您使用的是形式
,你需要使用fields_for
並編輯它:
#app/controllers/meals_controller.rb
class MealsController < ApplicationController
def edit
@meal = Meal.find params[:id]
end
private
def meal_params
params.require(:meal).permit(meal_ingredient_attributes: [:amount])
end
end
#app/views/meals/edit.html.erb
<%= form_for @meal do |f| %>
<%= fields_for :meal_ingredients do |i| %>
<%= f.object.ingredient.name #-> meal_ingredient belongs_to ingredient %>
<%= i.number_field :amount %>
<% end %>
<%= f.submit %>
<% end %>
以上將o輸入配料清單並允許您輸入「金額」值。
至於複選框,我不得不做一個演示應用程序,看看我能否得到這個工作。如果您覺得有必要,我可以做到這一點。
另一種方法是用has_and_belongs_to_many
:
#app/models/meal.rb
class Meal < ActiveRecord::Base
has_and_belongs_to_many :ingredients do
def amount #-> @meal.ingredients.first.amount
...........
end
end
end
#app/models/ingredient.rb
class Ingredient < ActiveRecord::Base
has_and_belongs_to_many :meals
end
這樣一來,你就可以添加儘可能多的meals
/ingredients
所需,讓您與@meal.ingredients.where(ingredients: {id: "x" }).size
找到「量」。你也可以製作一個方法來簡化它(上圖)。
你不會需要使用fields_for
此:
#app/controllers/meals_controller.rb
class MealsController < ApplicationController
def new
@meal = Meal.new
end
def edit
@meal = Meal.find params[:id]
end
def update
@meal = Meal.find params[:id]
@meal.save
end
def create
@meal = Meal.new meal_params
@meal.save
end
private
def meal_params
params.require(:meal).permit(ingredient_ids: [])
end
end
因爲HABTM記錄使用模型中的has_many
協會,它爲您提供了collection_singular_ids
方法。這使您可以覆蓋相關數據,而無需fields_for
:
#app/views/meals/new.html.erb
<%= form_for @meal do |f| %>
<%= f.collection_check_boxes :ingredient_ids, Ingredient.all, :id, :name %>
<%= f.submit %>
<% end %>
如果你想添加額外的成分,你需要創建JS複製的複選框元素。這將允許您向控制器提交多個ids
,該控制器只會將它們盲插入數據庫。
此方法覆蓋成分列表,並且只適用於在habtm關聯/表格上沒有任何唯一性約束的情況。
該鏈接不再有效,你能夠重新託管,或至少指向你的源代碼? – arielkirkwood
由於我使用了臨時電子郵件,帳戶被暫停。我會在一分鐘內爲你重新上傳 –