简体   繁体   English

Rails获得相关模型

[英]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: 在每行上使用debug时,它只显示以下数据:

---
- !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. :class_name选项告诉Rails ......类名。 Here (I'm assuming) you don't have a class called UserFrom or UserTo. 在这里(我假设)您没有名为UserFrom或UserTo的类。 You have one class called User in app/models. 您在app / models中有一个名为User的类。

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. 我将假设外键设置正确,并且它们都包含用户ID,即使它们没有_id后缀。

As for @mails , your query should work. 至于@mails ,您的查询应该有效。 But it would be easier if you declared a has_many :mails association on your user. 但如果您在用户上声明了has_many :mails关联会更容易。 This would allow you to do something like current_user.mails . 这将允许您执行类似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. 我还建议您重命名外键,如“sender_id”和“receiver_id”,以提高可读性。

Usage: 用法:

@mails = Mail.where(sender: current_user)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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