2012-09-01 34 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不會將其已發佈屬性設置爲true。

您需要做的是擴展published_tags關聯並覆蓋它的方法,以便在插入時將發佈的屬性設置爲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」關聯... – gayavat

+0

可以使用default_scope添加兩個模型PublishedPostsTag和PrivatePostsTag,但它看起來有點難看。 – gayavat

+0

在這種情況下published_tag_ids doesn'w工作 – gayavat