rails_admin插件在has_many:through关系上使用嵌套表单的问题

时间:2013-02-19 02:59:54

标签: ruby-on-rails ruby rails-admin

我有一个似乎是一个cookie切割器问题,甚至在这里有一个相关的wiki页面:https://github.com/sferik/rails_admin/wiki/Has-many-%3Athrough-association

我会尽量简短。我正在构建的应用程序中有一个has_many:through关系。涉及的模型如下:

运动员,运动员角色,SportRole。

sport_roles表中列出了运动员可以拥有的一般角色,如一垒手,二垒手等。 athlete_roles表是包含athlete_id和sport_id的多对多连接表。

我的模型在下面用代码示例定义。我只是希望能够创建一名运动员,并将他们与1+运动角色联系起来(最终将在athlete_roles表中创建1个以上的新记录)。它不应该问我一个Athle_id,因为运动员在后端和验证通过后调用保存之前不会有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

1 个答案:

答案 0 :(得分:0)

我认为这里的问题存在于你的模型中。

您正在描述的模型是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
相关问题