stergosz
stergosz

Reputation: 5860

ruby on rails before save update another table first

I am trying to update another associated table before saving but i am getting into errors i am not familiar with...

so i have in my model

post.rb

  before_save :update_total_items

  def update_total_items
    b = Tags.find(:tag_id => self.tag_id)
    b.total_items = b.total_items+1
    b.save
  end

but i get an error

Unknown key tag_id

so how can i access the property i am adding before i save it in order to use it and update an existing associated on another table?

Upvotes: 0

Views: 2228

Answers (2)

Kyle C
Kyle C

Reputation: 4097

The Post object does not have a foreign key tag_id, change it to

  b = self.tags.find(:post_id => self.id)

This is assuming Post has_many :tags , and Tag belongs_to :post

and I agree with @tadman that you should use the increment method, increment(attribute, by = 1)

Upvotes: 1

tadman
tadman

Reputation: 211560

Usually the id of a model is called just that. Generally what you want is:

b = Tags.find(self.tag_id)

Be aware this might throw an ActiveRecord::RecordNotFound exception if no record could be found. A safer approach is:

if (b = Tags.where(:id => self.tag_id).first)
  b.increment!(:total_items)
end

Avoid loading and saving to increment a value. You may end up with an ugly race condition where you lose counts.

As a note, it's highly irregular that your model is called Tags. It should be called Tag.

Upvotes: 2

Related Questions