【问题标题】:How to Join more than 2 tables in Ruby on Rails?如何在 Ruby on Rails 中加入 2 个以上的表?
【发布时间】:2016-05-20 11:26:51
【问题描述】:

我有 4 个表 usersuser_detailscategoriesgalleries 我想在一个查询中显示所有记录。请参阅下面我的表结构

类别

id
name

用户

id
username
email
password
user_type
is_active (0 or 1)
created_at
modified_at

user_details

id
user_id
category_id
name
gender
address
phone

画廊

id
user_id
name
image
is_active

我想通过 user_details 和 category 获取用户 id=1 的所有用户信息,并向她/她显示 galleries 表中的所有 is_active=1 图像

这是我的代码 -

@user_details = User.eager_load(:Category,:Gallery,:UserDetail).where('users.id'=>20, 'users.is_active'=>1, 'users.user_type'=>2, 'galleries.is_active'=>1).first()

这里我收到错误消息:

Association named 'Category' was not found on User; perhaps you misspelled it?

实际上我在UserDetails 模型中关联了Category。所以我无法获得Category 数据。请查看我的所有型号 -

category.rb

class Category < ActiveRecord::Base
  has_many :UserDetail
end

user.rb

class User < ActiveRecord::Base
  #before_save :encrypt_password
  has_one :UserDetail, dependent: :destroy
  has_many :Gallery, dependent: :destroy
end

user_detail.rb

class UserDetail < ActiveRecord::Base
  belongs_to :User
  belongs_to :Category
end

gallery.rb

class Gallery < ActiveRecord::Base
  belongs_to :User
end

让我知道为什么categories 表没有加入。请帮我解决这个问题。

【问题讨论】:

  • 为什么要定义这样的关联 has_many :UserDetail 它应该是 has_many :user_details
  • 不,我的模型关联工作正常。 UserDetail 也适合我。

标签: mysql ruby-on-rails ruby activerecord


【解决方案1】:

这里有一些事情。赶时间所以无法验证语法,但应该让你很接近

  1. 正确的关联命名 - 按照惯例,关联应该是模型的单数或复数小写蛇形大小写。所以画廊应该是

    类图库 属于_to:用户

    类用户 has_many :画廊

  2. 使用包含加载值并防止 n+1 查询

    User.includes(:categories, :user_detail, ,:user_detail)

  3. 为条件句使用范围 @user_details = User.eager_load(:Category,:Gallery,:UserDetail).where('users.id'=>20, 'users.is_active'=>1, 'users.user_type'=>2, 'galleries.is_active '=>1).first()

    类用户 范围:活动,-> {where(is_active: 1)} 类:of_type,->(id){ where(user_type:id)} 结束

然后有点像

User.active.of_type(2).includes(:categories, :user_detail, ,:user_detail, :galleries).where('galleries.is_active'=>1).first()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多