belongs_to sometimes prevents the object from being saved

Seems to be a bug. I can't dig into the core of it (since too many
models), but here is what I know.

I have a model user, which has primary key :id.
I also have a model of action. Two users interact with each other
through the model of action. Say, one user sends a comment to the
other. So, action model has primary key :id, and also :sender_id
and :receiver_id, which are ids of sender and receiver,
correspondingly. There is also a concept of rating. Receiver can rate
the sender for his comment. That is, rating doesn't have a primary
key, yet it has :user_id (which is the id of receiver) and :action_id.

The model for ACTION has:
belongs_to sender, :class_name => 'User', :foreign_key => :sender_id
belongs_to receiver, :class_name => 'User', :foreign_key
=> :receiver_id

The model for USER has:
has_many :sent_actions, :class_name => 'Action', :foreign_key
=> :sender_id
has_many :received_actions, :class_name => 'Action', :foreign_key
=> :receiver_id

The model for RATING has:
belongs_to :user
belongs_to :action

Now the funniest part. When I try to save new rating, it's not saved,
while rating has belongs_to :action. If this line is commented, then
everything is ok - rating is saved and rating.action_id is in place in
the database.

I dug into into save! of the ActiveRecord class and put a "raise
'testing...'" there instead of its usual code. Now, if
belongs_to :action is inside the model, then save! doesn't fire off
with an error, which means that rails doesn't even go inside save!. If
belongs_to :action is commented, then 'testing...' appear on the
screen, while trying to save a rating.

Did anyone bump into anything similar? How to override? Or it's a bug
and I need to forget about it and find working workaround? :slight_smile:

Thanks.

truetype wrote:

The model for RATING has:
belongs_to :user
belongs_to :action

Now the funniest part. When I try to save new rating, it's not saved,
while rating has belongs_to :action. If this line is commented, then
everything is ok - rating is saved and rating.action_id is in place in
the database.

I dug into into save! of the ActiveRecord class and put a "raise
'testing...'" there instead of its usual code. Now, if
belongs_to :action is inside the model, then save! doesn't fire off
with an error, which means that rails doesn't even go inside save!. If
belongs_to :action is commented, then 'testing...' appear on the
screen, while trying to save a rating.

Are you saying you're calling save! on the rating but the save! method
is never called? Is its associated action object new? Is the action
object valid? You can try adding validates_associated :action to the
Rating model. If that doesn't work, please post the relevant section
of your code.

The name 'action' has been reported to cause issues. Try using a
different name for the model