2012-09-01 3 views
0

레코드는 기본 범위로 추가되지만 필수는 아닙니다.기본 범위가있는 has_many를 통해 레코드 추가

class PostsTag 
    # published is false by default 
end 

class Post 
    has_many :posts_tags 

    {published: true, private: false}.each do |key, val| 
    has_many "#{key}_tags", 
     through: "posts_tags", 
     conditions: ["posts_tags.published = ?", val], 
     source: :tag 
    end 
end 

#-------------------- 

Post.first.published_tags << Tag.first 
Post.first.published_tags.count # = 0 
Post.first.private_tags.count # = 1 

내가 잘못 했습니까? 진심으로 감사드립니다.

답변

1

published_tags에 새 태그를 삽입해도 published 속성은 기본적으로 true로 설정되지 않습니다.

게시자가 수행해야하는 작업은 published_tags 연결을 확장하고 < < 메서드를 재정의하여 삽입시 published 속성을 true로 설정하는 것입니다.

has_many :published_tags do 
    def <<(tag) 
    tag.published = true 
    proxy_association.owner.posts_tags+= [tag] 
    end 
end 

내가 정확히이 경우 here의 전체 작업 예제를 작성했습니다, 당신은 확실히 좀 더 통찰력을 얻기 위해 그것을 살펴이 있어야합니다 코드는 그런 일을 찾을 것입니다.

+0

죄송합니다. 게시 된 깃발은 PostsTag 모델에 배치되어 있습니다. 당신의 대답은 간단한 has_many 연관에 대해서는 잘 작동하지만 "has_many through"associations에 대해 수정해야하는 것처럼 보입니다 ... – gayavat

+0

PublishedPostsTag와 PrivatePostsTag를 default_scope로 추가 할 수는 있지만보기에는 약간 엉망입니다. 이 경우 – gayavat

+0

published_tag_ids가 작동하지 않습니다. – gayavat

관련 문제