2017-02-27 43 views
0

我在rails的模型中遇到了关联问题。模型看不到has_many关系,得到

我有这样一段代码

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 

回答

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来查看当时的错误并检查对象。在这里会很容易。

+0

太棒了,它的作品像魅力!我一直在用''''''尝试一些东西,但绝对不会在那里:D谢谢!编辑:我使用RubyMine,因为我习惯了Java中的IntelliJ IDEA –

相关问题