Friday, October 21, 2022

[FIXED] How to correctly apply a has_many relationship with an order by in Ruby on Rails 6

Issue

I am creating a User model in Rails 6 to mirror a model that exists in a separate project. There is a has_many relationship that is causing some problems.

class User < ApplicationRecord
      has_many :activation_histories, inverse_of: :user , => { order "created_at  DESC"} 
end

The project I am basing this on used Rails 3.2 and worked successfully like this

class User < ApplicationRecord
       has_many :activation_histories, inverse_of: :user, order: "created_at desc" 
end

I can see from the official documentation the example using an order by looks as so

class Author < ApplicationRecord
  has_many :books, -> { order "date_confirmed DESC" }
end

I get an error that it is expecting '=>' rather than '->' when I run it as so, but when I use '=>' I am getting

app/models/user.rb:6: syntax error, unexpected =>
app/models/user.rb:6: syntax error, unexpected '}', expecting `end'
app/models/user.rb:6: syntax error, unexpected =>
app/models/user.rb:6: syntax error, unexpected '}', expecting `end'
app/models/user.rb:6: syntax error, unexpected =>
app/models/user.rb:6: syntax error, unexpected '}', expecting `end'

I am relatively new to Ruby on Rails and am not sure where I am going wrong here or how to proceed. Removing the inverse_of has no effect on the errors I am seeing.

Any advice on how to correctly use this would be appreciated.


Solution

Try changing

has_many :activation_histories, inverse_of: :user , -> { order "created_at  DESC"} 

to

has_many :activation_histories, -> { order "created_at  DESC"} , inverse_of: :user

Your scope should be your second argument. https://www.rubydoc.info/docs/rails/4.1.7/ActiveRecord%2FAssociations%2FClassMethods:has_many



Answered By - RHFS
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.