如何在从 belongs_to 模型调用的 class 方法中访问 belongs_to 模型

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

UserBook型号,一个用户有很多本书,一本书属于一个用户。

Book 有一个 class 方法 create_from_hash 并且该方法是从 User 模型调用的。

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

如何从 class 方法中获取 user_iduser 实例?

您需要将用户 ID 传递给 create_from_hash 方法。

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

您可以使用 hash 传递 id,另一方面使用 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