2008-09-21 80 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