如何从has_many:throught关联中获取字段

时间:2019-01-05 11:04:45

标签: ruby-on-rails ruby activerecord

我在RoomsUsers模型中具有多对多关联,在此模型中,我有一个角色字段,关联效果很好,但我无法访问此字段。 我的架构如下:

 create_table "messages", force: :cascade do |t|
   t.text "body"
   t.datetime "created_at", null: false
   t.datetime "updated_at", null: false
   t.integer "user_id"
   t.integer "room_id"
 end                                                                       
 create_table "rooms", force: :cascade do |t|
   t.string "name"
   t.datetime "created_at", null: false
   t.datetime "updated_at", null: false
   t.integer "rooms_user_id"
 end
 create_table "rooms_users", force: :cascade do |t|
   t.integer "user_id"
   t.integer "room_id"
   t.datetime "created_at", null: false
   t.datetime "updated_at", null: false
   t.string "role"
   t.integer "last_checked"
 end
create_table "users", force: :cascade do |t|
  t.string "name"
  t.string "password_digest"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.string "mail"
  t.integer "rooms_user_id"
end

用户模型:

class User < ApplicationRecord
  has_secure_password(validations: false)
  has_many :messages
  has_many :rooms_users
  has_many :rooms, through: :rooms_users
  accepts_nested_attributes_for :rooms_users
  attr_accessor :register, :mail_confirmation, :login
end

房间型号:

class Room < ApplicationRecord
  has_many :rooms_users
  has_many :users, through: :rooms_users
  accepts_nested_attributes_for :rooms_users
  has_many :message
end

RoomsUsers模型:

class RoomsUsers < ApplicationRecord
  belongs_to :user
  belongs_to :room
end

我正在尝试从第一个用户的房间获取角色字段。

User.first.rooms.first.role

它给我NoMethodError(#的未定义方法“ role”)。怎么了?

2 个答案:

答案 0 :(得分:1)

您正在尝试访问role表中的rooms字段,但该字段位于rooms_users表中。应该是:

User.first.rooms_users.first.role

并从rooms_user_idrooms表中删除users,您不需要

答案 1 :(得分:0)

如果要通过“房间”模型访问“角色”字段,则需要将“角色”字段的位置从Rooms_users表更改为Rooms表。这样做,您可以使用User.first.rooms.first.role访问“角色”。

但是,如果您想在rooms_users表中保留“角色”字段,那么您将需要使用User.first.rooms_users.first.role,因为Vasilisa已经提到过。

t.integer "rooms_user_id"在房间和用户表中不是必需的。房间和用户中使用的has_many已经在将rooms_users与他们链接。