开发者

belongs_to with :class_name behaving odd

I have 开发者_Python百科a Task model and User model.

A task can be assigned a user to process it, while a user can be assigned many tasks.

The field names are a little off so I am trying to use the class_name options etc, but for whatever reason I'm getting some odd results.

Task association

belongs_to :assigned_to, :class_name => 'User', :foreign_key => 'assigned_to'

User association

has_many :assigned_tasks, :class_name => 'Task', :foreign_key => 'assigned_to'

yet when I look at the sql being produced when a task is saved, it returns nil for the assigned_to id (it's an integer column).. and then when the Tasks/Index action is being called, I see it's attempting to pull a user where the id = null as it was saved with a null value in the field..

I've most likely done something wrong as I'm new to rails, so any assistance would be greatly appreciated.

Thanks


I was doing two things wrong:

  1. When I created the select tag, I forgot to include the :user portion so when the parameters were passed in, the user's id was outside of the user object.

  2. The belongs_to :assigned_to has the same name as the database column; when the parameters did come in properly once the select field was fixed, it was complaining about the value passed in not being an object. User expected, received string etc etc. Switching the association name fixed this, which makes 100% sense and why I should definitely change the database field name.


I think you need _id with the fk

:foreign_key => 'assigned_to_id'

I am assuming your db column name is assigned_to_id

Also, this is a really good resource http://guides.rubyonrails.org/association_basics.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜