Ruby On Rails Active Admin has_many changing dropdown to use a different column

試著忘記壹切 提交于 2019-12-19 04:02:16

问题


I am completely new to ActiveAdmin and RoR and i cant figure out how to change the visible value of the dropdowns in a has_many association.

Fillup Model

class Fillup < ActiveRecord::Base
    // key is car_id:integer
    belongs_to :car
end

Car Model

class Car < ActiveRecord::Base
    validates :description, :presence => true
    key is fillup_id:integer
    has_many :fillups
end

What it currently shows:

It currently shows im assuming an encoded reference to the Car assigned to it.

What i need it to show:

I need it to show the description given which is defined as description:string in the Car Model.


回答1:


Something like this should work...

In app/admin/model_name.rb

form do |f|
  f.inputs "My Model Name" do
    # add your other inputs
    f.input :cars, :collection => Car.all.map{ |car| [car.description, car.id] }
    f.buttons
  end 
end

Read this article to learn more about modifying the form.

AciveAdmin uses formtastic, you should read about that as well.




回答2:


In your Car model, just add something like :

def to_s
  description
end

It should do the job !

Explanation : Actually, your Car's to_s method returns the object id corresponding to the current instance, that's the default thing used when using a method like puts on an object. To replace a model's display name, you have to override this method and it will work anywhere in your app when you use puts @car or in your templates doing <%= @car %>



来源:https://stackoverflow.com/questions/10705372/ruby-on-rails-active-admin-has-many-changing-dropdown-to-use-a-different-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!