2016-08-18 12 views
1

我有一個has_many通過連接表設置爲食譜應用程序,其中IngredientMeal連接通過MealIngredient。在MealIngredient之內,我有meal_idingredient_idamount如何在Rails 4 HMT關聯中保存和更新連接表中的屬性?

我的問題是:如何保存和更新膳食形式的金額列?

添加的成分我的表單字段是這樣的:

<% Ingredient.all.each do |ingredient| %> 
    <label> 
    <%= check_box_tag "meal[ingredient_ids][]", ingredient.id, f.object.ingredients.include?(ingredient) %> 
    <%= ingredient.name %> 
    </label> 
    <br /> 
<% end %> 

如何保存量的每種成分?

我引用這個問題在這裏找到:Rails 4 Accessing Join Table Attributes

回答

2

我做了一個演示給你:http://meals-test2.herokuapp.com/new enter image description here

- 如果您使用的是形式

,你需要使用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關聯/表格上沒有任何唯一性約束的情況。

+0

該鏈接不再有效,你能夠重新託管,或至少指向你的源代碼? – arielkirkwood

+0

由於我使用了臨時電子郵件,帳戶被暫停。我會在一分鐘內爲你重新上傳 –

相關問題