domi91c
domi91c

Reputation: 2053

Accessing object rather an object ID in Rails

Using Devise, I can access an object's user with SomeModel.user, while the field is listed as user_id in the database schema. How can I do this with other ID fields? I have a model with two user fields; one from Devise, and a guest_id field. Can I use SomeModel.guest to access this second user object?

Upvotes: 0

Views: 31

Answers (2)

henggana
henggana

Reputation: 157

You want to add new relationship on SomeModel and in User.

class SomeModel < ActiveRecord::Base
  # -- some code
  belongs_to :guest, class: User
  # -- some code
end

class User < ActiveRecord::Base
  # -- some code
  has_many :some_models, foreign_key: :guest_id
  # -- some code
end

Upvotes: 1

archit gupta
archit gupta

Reputation: 1034

Write this in your model

belongs_to :guest, class_name: "User"

Upvotes: 1

Related Questions