【问题标题】:Rails 4 access table attributes from has_one associationRails 4 从 has_one 关联访问表属性
【发布时间】:2015-08-19 11:55:58
【问题描述】:

我有两个模型用户和帐户在哪里

class User < ActiveRecord::Base
  has_one :account
end

 class Account < ActiveRecord::Base
      belongs_to :User
    end

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

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

“列表”是我的模型中描述的检索记录的方法

在用户表中,我有两列“id”和“company_name” 在帐户表中,我将列作为“user_id”和“country”

现在我希望数组@user 检索公司名称和他们的国家,这可以通过帐户表中的 user_id 找到

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

【问题讨论】:

  • 你想要的输出数据应该是什么样子?
  • 当我写 User.each 时做|f| f.company_name f.country end 所以应该有公司名称和他们的国家
  • 你想只循环你的@user数组还是我可以提供另一种解决方案来检索用户?

标签: mysql ruby-on-rails ruby-on-rails-4 has-one


【解决方案1】:

在你的控制器中

@users = User.joins(:account)

你认为的

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

【讨论】:

    【解决方案2】:

    怎么样:

    # 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

    【讨论】:

    • 查询是否保持不变?
    • @Anatoly 有时使用 default_scope 进行调试是一场噩梦.. :) 使用命名范围更好。
    • @Anatoly 是的,我同意。
    猜你喜欢
    • 1970-01-01
    • 2013-12-25
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多