Home > other >  How to access belongs_to model in class method that is called from the belongs_to model
How to access belongs_to model in class method that is called from the belongs_to model

Time:05-20

There are User and Book model, a user has many books and a book belongs to a user.

The Book has a class method create_from_hash and the method is called from User model.

class User < ApplicationRecord
  has_many :books

  def create_book
    book_hash = {title: 'foo'}
    books.create_from_hash(book_hash)
  end
end

class Book < ApplicationRecord
  belongs_to :user
  def self.create_from_hash(book_hash)
    # NameError: undefined local variable or method
    p user_id 
  end
end

How can I get user_id or user instance from the class method?

CodePudding user response:

You need to pass the user id to the create_from_hash method.

class User < ApplicationRecord
  has_many :books

  def create_book
    book_hash = {title: 'foo'}
    books.create_from_hash(book_hash, self.id)
  end
end

class Book < ApplicationRecord
  belongs_to :user
  def self.create_from_hash(book_hash, user_id)
    puts user_id
  end
end

CodePudding user response:

You can pass id with the hash and on the other side get it with book_hash[:user_id]

class User < ApplicationRecord
  has_many :books

  def create_book
    book_hash = {title: 'foo', user_id: id}
    books.create_from_hash(book_hash)
  end
end

class Book < ApplicationRecord
  belongs_to :user
  def self.create_from_hash(book_hash)
    p book_hash[:user_id]
  end
end
  • Related