Rails 2:has_many:通过验证?

时间:2010-03-22 14:49:02

标签: ruby-on-rails orm has-many-through has-many-polymorphs

Rails 2.1.0(由于几个限制,暂时无法升级) 我正在努力实现这一目标。任何提示?

  1. 项目通过加入模型有很多用户
  2. 用户通过加入模式有很多项目
  3. Admin类继承User类。它还有一些特定于管理员的东西。
  4. 管理员,如主管和运营商的继承
  5. 项目有一个管理员,一个主管和许多运营商。
  6. 现在我想 1.以单一项目形式提交项目,管理员,主管和操作员的数据 2.验证所有并在项目表单上显示错误。

    Project has_many :projects_users ; has_many :users, :through => :projects_users
    User has_many :projects_users ; has_many :projects, :through => :projects_users
    ProjectsUser = :id integer, :user_id :integer, :project_id :integer
    ProjectUser belongs_to :project, belongs_to :user
    Admin < User # User has 'type:string' column for STI
    Supervisor < User
    Operator < User
    

    方法是否正确?欢迎提出任何建议。

3 个答案:

答案 0 :(得分:0)

我猜单表继承和嵌套表单可以帮到你。您可能想在文档中阅读它。 http://api.rubyonrails.org/classes/ActiveRecord/Base.html

答案 1 :(得分:0)

我发现答案在于使用has_many的单表继承:通过

class Project < ActiveRecord::Base
  has_many :projects_users, :dependent => :destroy
  has_many :users, :through => :projects_users, :dependent => :destroy
  has_one :admin, :through => :projects_users, :source => :user, :conditions => {:type => "Admin"}
  has_one :supervisor, :through => :projects_users, :source => :user, :conditions => {:type => "Supervisor"}
  has_many :operators, :through => :projects_users, :source => :user, :conditions => {:type => "Operator"}
  validates_presence_of :name
  validates_associated :admin

  def admin_attributes=(attributes)
    # build an admin object and apply to this relation
  end

  def supervisor_attributes=(attributes)
    # build a supervisor object and apply to this relation
  end

  def operator_attributes=(operator_attributes)
    operator_attributes.each do |attributes|
      # build an operator object for each set of attributes and apply to this relation
    end
  end
end

class User < ActiveRecord::Base
  has_many :projects_users, :dependent => :destroy
  has_many :projects, :through => :projects_users, :dependent => :destroy
  validates_presence_of :name
  validates_associated :projects
end

class ProjectsUser < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
end

class Admin < User
end

class Supervisor < User
end

class Operator < User
end

现在我们可以拥有以下

project1.users # User objects for admin, supervisor and operators
project1.admin # User object for Admin
project1.supervisor # User object for Supervisor
project1.operators # User objects for Operator

包含所有这些的复杂形式可以有

<% form_for :project ...
    <% fields_for "project[admin_attributes]", @project.admin do |admin_form|
    ...
    <% @project.operators.each do |operator| %>
        <% fields_for "project[operator_attributes][]", operator do |operator_form| %>

依旧......

答案 2 :(得分:0)

我最终使用了管理员,主管和操作员的虚拟属性 其他一切都通过ORM协会