Search code examples
rails-adminbelongs-to

rails admin belongs to dropdown list


I manage my database from an admin page, and would like to assign a group to indics from a dropdown list.

So what I have for the moment :

indic table:

id       | int(11)      | PRIMARY 
name     | varchar(255) |
group_id | int(11)      |

group table:

id       | int(11)      | PRIMARY 
name     | varchar(255) |

indic.rb:

belongs_to :group

rails_admin do 
  list do 
    field :id
    field :name
    field :group_id
  end
  edit do
    field :name
    field :group_id
  end
end

group.rb:

has_many :indic

rails_admin do 
  list do 
    field :id
    field :name
  end
  edit do
    field :name
  end
end

With this there is no dropdown (I mean choose group from a list with every group from the database), and I'm not even sure they are linked cause I can put group_id that doesn't exist in group table.

I found on other answer that I need to change the edit field to field :group_id, :belongs_to_association but if I do it I get an error loading the page :

Showing /home/ma/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/rails_admin-0.6.5/app/views/rails_admin/main/edit.html.haml where line #2 raised:

undefined method `klass' for #< RailsAdmin::Adapters::ActiveRecord::Property:0x007fd3f99d1e38 >

= rails_admin_form_for @object, url: edit_path(@abstract_model, @object.id), as: @abstract_model.param_key, html: { method: "put", multipart: true, class: "form-horizontal denser", data: { title: @page_name } } do |form|

= form.generate action: :update

Anyone know how to fix that problem ? Also for the dropdown, list of id would be nice, but a perfect solution (I don't know if it's possible) would be to list names for those group.id.


Solution

  • I finally found the solution, which is really stupid, the link was not done because some misstake about the "s" at the end of key words, and the edit must be done on the table, not the id column

    here's the correct solution :

    indicator.rb:

    belongs_to :group   # no "s" for belongs_to
    
    rails_admin
      ...      
        edit
          field :group  # table name, not the name of the reference column !
      ...
    

    indic.rb:

    has_many :indics   # need "s" for has_many
    

    With this everything works as expected, and the list is with the name by default, so my bonus is also done :)