Rails 4 个从 has_one 关联访问 table 属性

Rails 4 access table attributes from has_one association

我有两个模型用户和帐户

class User < ActiveRecord::Base
  has_one :account
end

 class Account < ActiveRecord::Base
      belongs_to :User
    end

在我的用户控制器中,我通过

检索用户
@user = User.list('', false,'company', 'asc')

其中 "list" 是我的模型中描述的检索记录的方法

在用户 table 中我有两列 "id" 和 "company_name" 在帐户 table 中,我的列为 "user_id" 和 "country"

现在我想让数组@user 检索公司名称和他们的国家,这可以通过 user_id 在帐户 table

中找到

请告诉我该怎么做 提前谢谢

在你的控制器中

@users = User.joins(:account)

你眼中的

@users.each do |user|
  user.company_name
  user.account.country
end

怎么样:

# app/models/user.rb
class User < ActiveRecord::Base
  has_one :account

  scope :with_account_info, -> { includes(:account) }
  default_scope{with_account_info}
end

如果您愿意,可以将最后两行合并为一行,即:

default_scope{ includes(:account) } 

HTH