无法在Rails 5项目中使用“includes”访问ActiveRecord关系

时间:2016-09-03 08:31:35

标签: ruby-on-rails activerecord rails-activerecord ruby-on-rails-5

我正在使用Rails 5和MySQL数据库,这就是我的模型的样子:

class User < ApplicationRecord
  has_many :user_activities
end
# Table: "users"

class UserActivity < ApplicationRecord
  belongs_to :user
end
# Table: "user_activities"

为了清楚说明我想要实现的目标,我将首先向您展示一个实际工作的查询:

SELECT * FROM user_activities LEFT JOIN users ON users.id = user_activities.user_id WHERE (users.gender = 'female') LIMIT 1;

没什么特别的,对吗?问题是我并没有真正在我的Rails项目中使用它。我已经阅读了一些文章,但不知怎的,我被卡住了......

ua = UserActivity.includes(:user).where(users: {gender: 'female'}).limit(1) # <-- The "join" part of it works
# ua = UserActivity.includes(:user).where("users.gender = 'f'").limit(1) # <-- MySQL throws an error
puts ua.inspect # <-- Shows me only the attributes of my UserActivity class

puts ua.user.inspect # <-- Can't access anything

所以我的问题是为什么我不能使用“ua.user”?

3 个答案:

答案 0 :(得分:0)

  

ua = UserActivity.includes(:user).where(&#34; users.gender =&#39; f&#39;&#34;)。limit(1)#&lt; - MySQL抛出错误

包含在单独的查询中加载关联数据,您应该使用eager_load,或者您可以使用

UserActivity.includes(:users).references(:users).where("users.gender = 'f'").limit(1)

答案 1 :(得分:0)

试试这个

ua = UserActivity.eager_load(:user).where({users: {gender: 'female'}}).limit(1)

答案 2 :(得分:0)

试试这个

@user_activities = UserActivity.joins(:user).where("users.gender = female"})

此处@user_activities为您提供数组

@user_activities.each do |user_activity|
  user_activity.foo # It Will Give Their Class Attributes Values
  user_activity.try(:user).try(:gender)  # It Will Give User Class Attributes Values
end