wyc
wyc

Reputation: 55273

Update attribute of Post model with tags each time they are created or saved?

I have Post model:

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

  has_and_belongs_to_many :tags
end

and a Tag model:

class Tag < ActiveRecord::Base
  attr_accessible :name

  has_and_belongs_to_many :posts
  end
end

As you can see they have a has_and belongs_to_many association with each other and I also created a joint table:

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

I want to do the following:

Each time a post's tag(s) are created or saved the tag_list attribute of the post that the tags belong to should update with the tags.

Any suggestions to accomplish this?

Upvotes: 1

Views: 127

Answers (1)

prasvin
prasvin

Reputation: 3009

I suggest adding an after_save callback to Tag model.

after_save :update_tag_list_on_posts

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

Upvotes: 1

Related Questions