I'm having trouble with association in rails' model.
I got such piece of code
class Member < ApplicationRecord
has_many :rooms
has_many :tokens, dependent: :destroy
has_secure_password
//[...] - some validations not according to my model
Then in my controller I have
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
Recently everything worked as it should. Now, after creating tokens table + adding that to models it says
"status": 500,
"error": "Internal Server Error",
"exception": "#<NoMethodError: undefined method `rooms' for #<Member::ActiveRecord_Relation:0x00560114fbf1d8>>",
I'm getting user with this method.
def authenticate_token
authenticate_with_http_token do |token, options|
@current_member = Member.joins(:tokens).where(:tokens => { :token => token })
end
end
This will need to change to get an instance (not a relation). Just add first
to the end.
authenticate_with_http_token do |token, options|
@current_member = Member.joins(:tokens).where(:tokens => { :token => token }).first
end
Note, the error is on the ActiveRecord_Relation
object.
Also, not sure how you are debugging, but I recommend using https://github.com/charliesome/better_errors to see the error at the time and inspect the objects. Would have been an easy catch here.