0

I have been working with Rails 3.0.5 and Ruby 1.9.2 and I have noticed that a new record doesn't get saved or isn't available for use instantly.

For example

def create    
    @some_record = Pool.new(params[:pool])  
      @some_record.users.push(current_user)
    if params[:commit] == "Add More"          
      @some_record.save        
      @some_record.do_something
    elsif params[:commit] == "Save"
      do_something_else(params)
    elsif params[:commit] == 'Cancel'
      redirect_to user_url(current_user)
    end    
 redirect_to some_other_url(current_user)
end

So when I save the record and call some_record.do_something the saved object isn't available instantly. current_user.some_records doesn't contain the newly added record but current_user.some_records.all displays the newly saved record. However on the console I am able to view the newly created record with current_user.some_records.

I'm sure I am missing something fundamental to Rails 3. I have also tried the same with current_user.some_records.build(params[:some_record] and I have the same problem. Does Rails 3 save the object instantly or is there some kind of delayed write/save because the same problem does not occur with Rails 3.0.3.

Also I am not using an authentication plugin like authlogic/devise and I simply save the current_user object to the session. I am not sure what I am doing wrong. WOuld appreciate any help?

Its also a many-to-many association between some_record and users

Sid
  • 6,134
  • 9
  • 34
  • 57
  • Sorry Big mistake on my part. The save is called after the push to the association array. – Sid Mar 27 '11 at 10:40

2 Answers2

1
current_user.some_records 

does not contain the newly added record because you did not save the operation after assigning @some_record.users.push(current_user). All you have to do is to add .save after the assignment and it should work.

hkairi
  • 385
  • 2
  • 9
1

The model structure is not clear from your question but let's assumed that current_user belongs_to some_records To force a database read try this:

current_user.some_records(true)

By default forcereload = false, to override this you should pass true

megas
  • 21,401
  • 12
  • 79
  • 130
  • I don't understand. You mean a database read is not a default setting and needs to be explicitly called. Whats the advantage/use of such a setting. – Sid Mar 27 '11 at 10:48
  • Doesn't development mode reload everything implicitly. – Sid Mar 27 '11 at 10:50
  • "If the associated object has already been retrieved from the database for this object, the cached version will be returned" - from here http://guides.rubyonrails.org/association_basics.html – megas Mar 27 '11 at 11:05