2008-09-21 6 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 메서드에 정의되어 있는지 확인하려면 어떻게하면 (우아하게) ingredients_string의 뷰를 알 수 있습니까?

+0

미안 해요, 난 정말 당신이 요구하는지 이해가 안 돼요. 해결하려는 문제는 무엇입니까? 어떻게 사용되는지, 어디에서 고장이 나는지에 대한 예를들 수 있습니까? – bhollis

답변

0

이 두 가지를 함께 사용하면 문제가 발생할 수 있습니다.

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 

참고 I : 둘 다, 이런 식으로 뭔가를

attr_accessor :ingredients_string 

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

attr_accessor 제거하십시오 다른 일을 ingredients_string 방법은 before_save, set_ingredients 방법을 정의하고 자신의 ingredients_string= 방법을 정의하기 위해 노력하고있다 set_ingredients의 구현을 빌려 줬습니다. 그 문자열을 분해하고 필요에 따라 성분 모델 연관을 생성/삭제하는 좀 더 우아한 방법이 있을지 모르지만, 늦었고 지금 당장 생각할 수 없습니다. :)

0

이전 답변은 매우 좋았지 만 몇 가지 변경 사항이있을 수 있습니다.

def ingredients_string = (텍스트) ingredients.each {| x | x.destroy} text.blank가 아닌 경우? text.split ("\ n"). 각각 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 메소드로 설정됩니다. 그래도 고마워! –

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 
관련 문제