模型看不到 has_many 关系,正在获取

Model can't see has_many relation, getting

我在 rails' 模型中遇到关联问题。

我得到了这样一段代码

class Member < ApplicationRecord
  has_many :rooms
  has_many :tokens, dependent: :destroy

  has_secure_password
  //[...] - some validations not according to my model

然后在我的控制器中我有

def create
  unique_id = SecureRandom.uuid
  @room = @current_member.rooms.new(unique_id: unique_id)
  @room_details = RoomDetail.new(video_url: 'test', room: @room)

  if @room.save
    render json: @room, status: :created, location: @room
  else
    render json: @room.errors, status: :unprocessable_entity
  end
end

最近一切正常。现在,在创建令牌 table + 将其添加到模型后,它说

"status": 500,
"error": "Internal Server Error",
"exception": "#<NoMethodError: undefined method `rooms' for #<Member::ActiveRecord_Relation:0x00560114fbf1d8>>",

我正在使用这种方法获取用户。

def authenticate_token
  authenticate_with_http_token do |token, options|
    @current_member = Member.joins(:tokens).where(:tokens => { :token => token })
  end
end

这将需要更改以获取实例(而非关系)。只需在末尾添加 first

authenticate_with_http_token do |token, options|
    @current_member = Member.joins(:tokens).where(:tokens => { :token => token }).first
end

注意,错误在 ActiveRecord_Relation 对象上。

此外,不确定您是如何调试的,但我建议使用 https://github.com/charliesome/better_errors 来查看当时的错误并检查对象。在这里很容易抓住。