2010-02-21 7 views
0

내 예 :레일 액티브 업데이트 필드

방법이 tag_string 필드를 최적화 할

class Category < ActiveRecord::Base 
    has_many :tags, :as => :tagable, :dependent => :destroy 

    def tag_string 
    str = '' 
    tags.each_with_index do |t, i| 
     str+= i > 0 ? ', ' : '' 
     str+= t.tag 
    end 
    str 
    end 

    def tag_string=(str) 
    tags.delete_all 
    Tag.parse_string(str).each { |t| tags.build(:tag => t.strip) } 
    end 

end 
? 나는 단지 그 (것)들을 새롭게하고 싶을 때마다 모든 꼬리표를 삭제하고 싶지 않다. 문자열을 태그로 파싱하는 더 좋은 방법이 있습니까? 플러그인을 사용하고 싶지 않습니다! 고마워.

+0

왜 플러그인을 사용하지 않으시겠습니까? 다른 사람들은이 기능을 완벽하게 코딩하고 테스트하여 사용자가하지 않아도됩니다. 질문에 설명 된 태깅 관계는 비효율적이며 어색하고 태그의 최상의 기능 태그를 사용할 수 없게 만듭니다. – EmFi

답변

2

나는 플러그인을 사용하고 싶지 않지만,이 상황을 어떻게 처리하고 있는지 보려면 acts_as_taggable_on_steroids 소스를 파헤쳐보고 싶을 것입니다. 내 경험에 비추어 볼 때, 그 플러그인으로 작업하는 것은 매우 힘들었습니다.

1
class Category < ActiveRecord::Base 
    has_many :tags, :as => :tagable, :dependent => :destroy 

    def tag_string 
    tags.map {|t| t.name }.join ', ' 
    end 

    def tag_string=(str) 
    tags = Tag.parse_string(str) 
    end 

end 

무엇이 Tag.parse_string(str) 방법인지 잘 모릅니다. Tag 오브젝트의 배열을 리턴하면, 필자의 예제보다 효과가 있습니다. 그리고 이것이 단지 업데이트 할 것인지, 오래된 것을 지우고 새 것을 추가 할 것인지 확신 할 수 없습니다. 그것을 테스트하고 로그에서 실제로 무엇을 볼 수 있습니다.

1

다른 의견에 동의합니다. 여기에서 플러그인을 사용하는 것이 좋습니다. 여기에 하나의 해결책이 있습니다.

class Category < ActiveRecord::Base 
    has_many :tags, :as => :tagable, :dependent => :destroy 

    def tag_string 
    tags.collect(&:name).join(", ") 
    end 

    def tag_string=(str) 
    # Next line will delete the old association and create 
    # new(based on the passed str). 
    # If the Category is new, then save it after the call. 
    tags = Tag.create(str.split(",").collect{ |name| {:name => name.strip} }) 
    end 

end 
+0

나는 tag_string = (str)이 할 트릭을하지 않는다. 내가 잘못? – xpepermint

+0

답변을 변경했습니다. 그것은 작동해야합니다. –