【问题标题】:Model can't see has_many relation, getting模型看不到 has_many 关系,得到
【发布时间】:2017-02-27 19:41:49
【问题描述】:

我在使用 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

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

"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

【问题讨论】:

    标签: ruby-on-rails database models


    【解决方案1】:

    这需要更改以获取实例(而不是关系)。只需在末尾添加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 来查看当时的错误并检查对象。在这里很容易抓住。

    【讨论】:

    • 太棒了,它就像魅力一样!我一直在尝试first,但绝对不存在:D 谢谢!编辑:我使用 RubyMine,因为我习惯了 Java 中的 IntelliJ IDEA
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    相关资源
    最近更新 更多