2012-04-14 86 views
6

我對Ruby on Rails使用Active Admin gem。 我有模塊Team and Coach,它們有has_many和belongs_to的關係。ActiveAdmin表單(新/編輯)belongs_to關聯?

class Team < ActiveRecord::Base 
    belongs_to :coach 
end 

class Coach < ActiveRecord::Base 
    has_many :teams 
end 

我想出如何索引並顯示網頁上顯示的姓氏和名字(我做了這樣的:)

index do 
    column :name 
    column "Coach" do |team| 
     team.coach.firstname + " " + team.coach.lastname 
    end 
    default_actions 
    end 

我要的是如何顯示名字和姓氏團隊形式(新的和編輯頁面)的教練在下拉菜單中? 請幫我這個。

回答

7

你可以試試這個

f.input :coach_name, :as => :select, :collection => Coach.all.map {|u| [u.firstname, u.id]}, :include_blank => false 
3

我有同樣的問題。編輯頁面顯示對象實例的選擇菜單,例如,

#<Coach:0x00eff180c85c8> 

爲了解決它,並訪問每個實例的字段使用此,

form do |f| 
    f.inputs "Coaches" do 
    f.input :name 
    f.input :coach, member_label: Proc.new { |c| "#{c.firstname} #{c.lastname}" 
    end 
    f.actions 
end 

ActiveAdmin使用Formtastic及其documentation有更多的例子。

這個stackoverflow answer幫助我得到這個解決方案。

3

試試這個:

f.input :coach_name, :as => :select, :collection => Coach.all.map {|u| [u.firstname.to_s, u.id]}