我有一个has_many通过连接表设置一个食谱应用程序,其中Ingredient和Meal通过MealIngredient连接.在MealIngredient中,我有meal_id,ingredients_id和amount.我的问题是:如何访问金额列?
在我的食谱中,我循环了成分:
@meal.ingredients.each do |i|
我可以访问成分的属性,但不能从MealIngredient加入记录中获取数量.
我尝试使用包含在查询中做的@ meal.ingredients.includes(:meal_ingredients),但我不确定如何访问上述循环中的金额.当我使用i.inspect时,根本看不到有关meal_ingredients表的任何引用.
有没有办法使用i.amount访问该循环中的变量?
预先感谢您的任何帮助!
解决方法
啊,老老好,我如何访问我的额外的连接表属性问题.在MONTHS的努力下,直到我们想出了一个解决方案
–
ActiveRecord Association Extensions
您所遇到的问题是,Rails将只使用连接表中的foreign_keys
来加载您需要的关联数据.除非你真的直接加载连接模型,否则它不会给你访问连接属性的能力
一些搜索引导我们进入ActiveRecord关联扩展 – 一种访问不同ActiveRecord关联之间的中间数据的方法(使用一个名为proxy_association的集合).这将允许您从连接模型访问额外的属性,将它们附加到“原始”模型中:
#app/models/ingredient.rb class Ingredient < ActiveRecord::Base attr_accessor :amount #-> need a setter/getter end #app/models/meal.rb class Meal < ActiveRecord::Base has_many :meal_ingredients has_many :ingredients,through: :meal_ingredients,extend: IngredientAmount end #app/models/concerns/ingerdient_amount.rb module IngredientAmount #Load def load amounts.each do |amount| proxy_association.target << amount end end #Private private #Amounts def amounts return_array = [] through_collection.each_with_index do |through,i| associate = through.send(reflection_name) associate.assign_attributes({amount: items[i]}) if items[i].present? return_array.concat Array.new(1).fill( associate ) end return_array end ####################### # Variables # ####################### #Association def reflection_name proxy_association.source_reflection.name end #Foreign Key def through_source_key proxy_association.reflection.source_reflection.foreign_key end #Primary Key def through_primary_key proxy_association.reflection.through_reflection.active_record_primary_key end #Through Name def through_name proxy_association.reflection.through_reflection.name end #Through def through_collection proxy_association.owner.send through_name end #Captions def items through_collection.map(&:amount) end #Target def target_collection #load_target proxy_association.target end end
@meal = Meal.find 1 @meal.ingredients.each do |ingredient| ingredient.amount end