我有一个似乎是千篇一律的问题,甚至在这里有一个相关的维基页面:https://github.com/sferik/rails_admin/wiki/Has-many-%3Athrough-association
我会尽量简短。我在正在构建的应用程序中有一个 has_many :through 关系。涉及的模型如下:
运动员、AthleteRole、SportRole。
sport_roles 表包含运动员可以担任的通用角色列表,例如一垒手、二垒手等。 athlete_roles 表是包含 athlete_id 和 sport_id 的多对多连接表。
我的模型在下面用代码示例定义。我只是希望能够创建一个运动员并将他们与 1 个以上的运动角色相关联(最终将在 athlete_roles 表中创建 1 个以上的新记录)。它不应该向我询问 athlete_id,因为在后端调用 save 并通过验证之前,运动员不会有 id。我不需要在这里创建新的 sport_roles。我们假设正在创建的新运动员可以承担的所有角色都已经预定义。
** 编辑 **
澄清一下,我的问题是,如何使用 rails_admin 插件,而不是以独立形式为运动员选择一个或多个现有的运动角色?我不希望创建新的运动角色,但我希望能够在创建运动员时选择一个或两个现有的角色,并将该数据反射(reflect)在 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
最佳答案
我认为这里的问题在于您的模型。
您所描述的模型是 has and belongs to many relation应该是这样的:
运动员:
class Athlete < ActiveRecord::Base
has_and_belongs_to_many :sport_roles
end
体育角色
class SportRole < ActiveRecord::Base
has_and_belongs_to_many :athletes
end
迁移应该如下所示:
运动员
class CreateAthletes < ActiveRecord::Migration
def change
create_table :athletes do |t|
t.timestamps
end
end
end
体育角色
class CreateSportRoles < ActiveRecord::Migration
def change
create_table :sport_roles do |t|
t.timestamps
end
end
end
运动员与运动角色的关系
class SportRolesAthletes < ActiveRecord::Migration
def change
create_table :sport_roles_athletes , :id => false do |t|
t.integer :sport_role_id
t.integer :athlete_id
end
end
end
关于ruby-on-rails - rails_admin 插件问题与 has_many 上的嵌套表单 :through relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14949096/