简体   繁体   中英

Rails get associated models

I have a model with two associations to the same model:

class Mail < ActiveRecord::Base
  belongs_to :user, :class_name => 'UserFrom', :foreign_key => 'user_from'
  belongs_to :user, :class_name => 'UserTo', :foreign_key => 'user_to'
end

When I run the following code in the index action it does not get the correct associated models, any suggestions?

@mails = Mail.where('user_to = ?', current_user.id)

When using debug on each row the data it only shows this:

---
- !ruby/object:Mail
  attributes:
    id: 1
    created_at: 2013-02-13 21:17:41.962000000 Z
    updated_at: 2013-02-13 21:17:41.962000000 Z
    user_to: 1
    user_from: 2
    subject: Testing
    body: Mail body blah blah blahhh
    read:
    read_at:

The :class_name option tells Rails well... the class name. Here (I'm assuming) you don't have a class called UserFrom or UserTo. You have one class called User in app/models.

class Mail < ActiveRecord::Base
  belongs_to :user_from, :class_name => 'User', :foreign_key => 'user_from'
  belongs_to :user_to,   :class_name => 'User', :foreign_key => 'user_to'
end

I am going to assume the foreign key is setup properly, and that both of them contain user IDs, even though they don't have an _id suffix.

As for @mails , your query should work. But it would be easier if you declared a has_many :mails association on your user. This would allow you to do something like current_user.mails .

You can't have relations named the same. You have to rename your relations, this is an example:

class Mail < ActiveRecord::Base
  belongs_to :sender, :class_name => 'User', :foreign_key => 'user_from'
  belongs_to :receiver, :class_name => 'User', :foreign_key => 'user_to'
end

I also recommand you to rename the foreign keys, like "sender_id" and "receiver_id" for more readability.

Usage:

@mails = Mail.where(sender: current_user)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM