如何使用此动态生成的字段保存模型?
时间:2020-03-06 14:29:58 来源:igfitidea点击:
我有一个看起来像这样的Rails模型:
class Recipe < ActiveRecord::Base has_many :ingredients attr_accessor :ingredients_string attr_accessible :title, :directions, :ingredients, :ingredients_string before_save :set_ingredients def ingredients_string ingredients.join("\n") end private def set_ingredients self.ingredients.each { |x| x.destroy } self.ingredients_string ||= false if self.ingredients_string self.ingredients_string.split("\n").each do |x| ingredient = Ingredient.create(:ingredient_string => x) self.ingredients << ingredient end end end end
这个想法是,当我从网页上创建成分时,我传入ingredients_string
并让模型将其全部整理出来。当然,如果我要编辑成分,则需要重新创建该字符串。错误的本质是:我如何(优雅地)通知Ingredient_string的视图,并且仍然查看是否在set_ingredients
方法中定义了ingredient_string
?
解决方案
一起使用这两个可能会引起问题。两者都试图定义一个可以做不同事情的ingredients_string
方法。
attr_accessor :ingredients_string def ingredients_string ingredients.join("\n") end
摆脱" attr_accessor"," before_save"," set_ingredients"方法,并定义自己的" ingredients_string ="方法,如下所示:
def ingredients_string=(ingredients) ingredients.each { |x| x.destroy } ingredients_string ||= false if ingredients_string ingredients_string.split("\n").each do |x| ingredient = Ingredient.create(:ingredient_string => x) self.ingredients << ingredient end end end
注意,我只是借用了我们对set_ingredients
的实现。可能有一种更优雅的方法来分解字符串并根据需要创建/删除"成分模型"关联,但是已经很晚了,我现在想不起来。 :)
先前的答案非常好,但是可以做一些更改。
def Ingredients_string =(文本)Ingredients.each {| x | x.destroy}除非text.blank? text.split(" \ n")。each | x |
成分= Ingredient.find_or_create_by_ingredient_string(:ingredient_string => x)self.ingredients
我基本上只是修改了奥托的答案:
class Recipe < ActiveRecord::Base has_many :ingredients attr_accessible :title, :directions, :ingredients, :ingredients_string def ingredients_string=(ingredient_string) ingredient_string ||= false if ingredient_string self.ingredients.each { |x| x.destroy } unless ingredient_string.blank? ingredient_string.split("\n").each do |x| ingredient = Ingredient.create(:ingredient_string => x) self.ingredients << ingredient end end end end def ingredients_string ingredients.join("\n") end end