DawgOnKing
DawgOnKing

Reputation: 31

RAILS || ActiveRecord::AssociationTypeMismatch: Error on new model object

I have a User model which belongs_to Pay model. So when a user is created, its (years) attribute is used to query the Pay model and return an object which contains a rate. Everything works if I query via:

class User < ApplicationRecord
  belongs_to :pay
end

* CONTROLLER ACTIONS *
@user = User.new(user_params)
@user.pay = Pay.find(1)
=> #< Pay object returned with attributes....>

But the following returns a ActiveRecord::AssociationTypeMismatch: ....... which is an instance of Pay::ActiveRecord_Relation

@user = User.new(user_params)
@user.pay = Pay.where("years = ?", @user.years) #FAILS

Also tried the following....

@user.pay = Pay.where(years: @user.years)
@user.pay = Pay.where(years: params[:years]

And even inputing a string....

@user.pay = Pay.where(years: "3")

So the query is returning an instance of ActiveRecord_Relation instead of an AssociationType??

Upvotes: 0

Views: 563

Answers (1)

Eyeslandic
Eyeslandic

Reputation: 14890

where always returns an ActiveRecord relation, find returns a single instance. You can use where like this for similar effect

@user.pay = Pay.where(years: @user.years).first

however a better way would be

@user.pay = Pay.find_by(years: @user.years)

Upvotes: 2

Related Questions