我有什麼似乎是,即使在這裏有一個相關的維基頁面一個俗套的問題:https://github.com/sferik/rails_admin/wiki/Has-many-%3Athrough-associationrails_admin插件的問題與一個嵌套的has_many形式:通過關係
我會盡量簡短。我正在構建的應用程序中有一個has_many:through關係。涉及的模型如下:
運動員,運動員角色,體育角色。
sport_roles表中列出了運動員可以擁有的一般角色,如一壘手,二壘手等。 athlete_roles表是包含athlete_id和sport_id的多對多連接表。
我的模型在下面用代碼示例進行定義。我只是想創建一名運動員,並將他們與1+個運動員角色聯繫起來(這將最終在athlete_roles表中創建1個以上的新紀錄)。它不應該問我一個athlete_id,因爲運動員在後臺調用save並通過驗證之前不會有id。我不需要在這裏創建新的sport_roles。我們將假設所有正在創建的新運動員都可以採用的角色已經預先定義好了。
**編輯**
爲了澄清,我的問題是,我如何才能選擇一個或多個現有體育角色使用rails_admin插件,而不是在一個獨立的形式運動員?我不想創造新的體育角色,但我希望能夠在創建運動員時選擇現有的一兩個,並將這些數據反映在athlete_roles表中。
下面的代碼。
class Athlete < ActiveRecord::Base
has_many :athlete_roles, :dependent => :delete_all, :autosave => true, :include => :sport_role
has_many :sport_roles, :through => :athlete_roles
attr_accessible :first_name
attr_accessible :middle_name
attr_accessible :last_name
attr_accessible :suffix_name
attr_accessible :birthdate
# FOR RAILS_ADMIN
# for a multiselect widget:
attr_accessible :sport_role_ids
accepts_nested_attributes_for :athlete_roles, :allow_destroy => true
attr_accessible :athlete_roles_attributes
end
class AthleteRole < ActiveRecord::Base
attr_accessible :athlete_id
attr_accessible :sport_role_id
# Associations
belongs_to :athlete
belongs_to :sport_role
# validations
validates :athlete_id,:presence=>true,:uniqueness=>{:scope => [:sport_role_id], :message => "is already associated with this Sport Role"}
validates :sport_role_id,:presence=> true
end
class SportRole < ActiveRecord::Base
has_many :athlete_roles, :dependent => :delete_all
has_many :athletes, :through => :athlete_roles
attr_accessible :name
attr_accessible :short_name
attr_accessible :description
attr_accessible :created_at
attr_accessible :updated_at
attr_accessible :athlete_ids
attr_accessible :athlete_role_ids
validates :name, :presence => true
validates :short_name, :presence => true
validates :description,:length=>{:maximum => 500, :allow_nil => true}
end
有什麼問題之間
關係?即:你究竟發生了什麼問題,你得到的錯誤信息是什麼? – 2013-02-19 03:07:09
我編輯了我的問題,使其更加明顯,我正在尋求幫助,對不起。 – randombits 2013-02-19 03:13:38
什麼不行?你有沒有收到任何錯誤信息? – Automatico 2013-02-25 23:37:25