lundi 20 juin 2016

How to apply scoping on associations in Rails Admin

I am newbie to Ruby, Rails and Rails Admin. I came to know about scopes in ActiveRecord. I want to apply scoping to associations at the time of editing a record using the Admin interface.

Example: I have a model named Post. A post is created by some User. A user can be an admin or a normal user distinguished by relational column is_admin. At the time of creating/editing a post using the Rails Admin interface, we have to allow selection from normal user list.

I have created scope normal_users for ActiveRecord User

class User < ActiveRecord::Base
  scope :normal_users, -> { where(is_admin: false) }
end

class Post < ActiveRecord::Base
  belongs_to :user
  rails_admin do
    edit do
        configure :user do
          # _____________ ? what goes here so that only normal users are listed.
        end
    end
  end
end

Now how can I use this 'normal_users' scope in the belongs_to association in the Post so that the dropdown for the field user in the Post resource lists only the normal users.

I have seen examples filtering associations/scopes in Rails. But I do not know how to use/configure this in Rails Admin.

1 commentaire:

  1. Really nice blog post. provided a helpful information. I hope that you will post more updates like this Ruby on Rails Online Course Hyderabad

    RépondreSupprimer