2012-03-02 15 views
1

型號:每次創建或保存時,都會使用標籤更新Post模型的屬性?

class Post < ActiveRecord::Base 
    attr_accessible :title, :content, :tag_list 

    has_and_belongs_to_many :tags 
end 

標籤型號:

class Tag < ActiveRecord::Base 
    attr_accessible :name 

    has_and_belongs_to_many :posts 
    end 
end 

正如你可以看到他們有一個has_and belongs_to_many相互關聯,我也創建了一個聯合表:

create_table :posts_tags, :id => false do | t | 
    t.integer :post_id, :tag_id 
end 

我想做以下幾點:

每次創建或保存帖子的標籤時,標籤所屬帖子的tag_list屬性都應該使用標籤進行更新。

任何建議來完成此?

回答

1

我建議爲標記模型添加一個after_save回調。

after_save :update_tag_list_on_posts 

private 
    def update_tag_list_on_posts 
    posts.update_all(:tag_list => desired_tag_list_value) 
    end 
+0

我沒有得到什麼tag_list服務的職位。這就是爲什麼我放置'desired_tag_list_value'來更新。你能詳細解釋一下嗎? – prasvin 2012-03-02 05:43:24

+0

感謝您的回覆。 tag_list存儲屬於帖子的每個標籤。在保存帖子時, – alexchenco 2012-03-02 05:57:39

+0

輸入字段中的標籤保存在tag_list – alexchenco 2012-03-02 06:10:27

相關問題