Nikita
Nikita

Reputation: 1

How to get fields from has_many :throught association

I have a many-to-many association throught RoomsUsers model and in this model i have a role field, association works well but i can't access this field. My schema looks like:

 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

User model:

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

Room model:

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

RoomsUsers model:

class RoomsUsers < ApplicationRecord
  belongs_to :user
  belongs_to :room
end

And i am trying to get role field from first user's room.

User.first.rooms.first.role

It give's me NoMethodError (undefined method `role' for #). What's wrong?

Upvotes: 0

Views: 295

Answers (2)

Kandy
Kandy

Reputation: 292

If you want to access "role" field through Rooms model, you will need to change the place of your "role" field from rooms_users table to rooms table. Doing it you can access "role" using User.first.rooms.first.role.

However if you want to keep "role" field in rooms_users table, so you will need to use User.first.rooms_users.first.role as Vasilisa has already mentioned.

t.integer "rooms_user_id" are not necessary in rooms and users tables. The has_many used in rooms and users are already linking rooms_users with them.

Upvotes: 0

Vasilisa
Vasilisa

Reputation: 4640

You're trying to access role field in the rooms table, but it is in rooms_users table. Should be:

User.first.rooms_users.first.role

And remove rooms_user_id from rooms and users table, you don't need it

Upvotes: 1

Related Questions