D
D
Dmitry Marinov2014-01-23 15:13:20
Ruby on Rails
Dmitry Marinov, 2014-01-23 15:13:20

rails. Filter and search by associations?

Good day!
I am writing my first Rails project using Rails Admin. There are two related models. I can't figure out how to sort/filter results by association attributes.
Here is a short code of the models.

#users.rb
class User < ActiveRecord::Base
  attr_accessible :role_id, :login, :name, :password, :privileged, :birthday, :region_id, :phone_number,
  has_many :points
end

#point.rb
class Point < ActiveRecord::Base
   attr_accessible :points, :user_id
   belongs_to :user
   
   RailsAdmin.config.model Point do
     list do
       field :user_phone_number do
         searchable user: :phone_number
         sortable :user_phone_number

         def value
           bindings[:object].user.phone_number
         end
       end

       field :user_id do
       end
     
     field :points do
     end
     end
   end
end

The :user_phone_number field is rendered but not sorted. Error like:
Mysql2::Error: Unknown column 'points.user_phone_number' in 'order clause': SELECT `points`.* FROM `points` ORDER BY points.user_phone_number asc LIMIT 20 OFFSET
0 filter by any field from Users.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
int03e, 2014-01-23
@int03e

I'm not familiar with the Rails Admin gem, but your error is due to a non-existent user_phone_number field in the database. Add this field to the database using a migration.
rails g migration add_user_phone_number_to_points user_phone_number:string
rake db:migrate
not null, model-level validations, and whatever else you like.

P
Piranis, 2014-04-03
@Piranis

Just recently I was looking for
rusrails.ru/active-record-associations#the-has-man...
stackoverflow.com/questions/4641500/rails-polymorp...
is it?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question