2008-09-21 79 views
0

我有一个滑轨模型,看起来是这样的:如何使用此动态生成的字段保存模型?

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,让模型排序这一切了。当然,如果我正在编辑一个成分,我需要重新创建该字符串。这个错误基本上是这样的:如何通知成分_字符串的视图(优雅地)并且仍然检查在set_ingredients方法中是否定义了ingredient_string

+0

对不起,我真的不明白你在问什么。你想解决什么问题?你能举一个例子说明它是如何使用以及它在哪里崩溃的? – bhollis 2008-09-21 04:53:08

回答

0

一起使用这两个可能会导致您的问题。两者都试图定义一个ingredients_string方法做不同的事情

attr_accessor :ingredients_string 

    def ingredients_string 
     ingredients.join("\n") 
    end 

摆脱attr_accessor后,before_saveset_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。根据需要,可能会有一种更好的方式来分解该字符串并创建/删除成分模型关联,但现在已经很晚了,现在我想不起来了。 :)

0

以前的答案是非常好的,但它可以做一些改变。

def ingredients_string =(text) ingredients.each {| x | x.destroy} 除非text.blank? text.split(“\ n”)。each do | x | 成分= Ingredient.find_or_create_by_ingredient_string(:ingredient_string => X) self.ingredients
+0

嗯,这实际上不是find_or_create_by的情况。配料独特。 IngredientTypes,otoh不是唯一的,它们使用find_or_create_by方法进行设置。虽然谢谢! – 2008-09-21 16:06:57

0

我基本上只是修改奥托的回答是:

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