在创建连接模型时是否有一种干净的Rails方式来设置属性?

时间:2010-10-16 08:14:53

标签: ruby-on-rails activerecord associations

我正在使用Rails 3并且在项目和用户之间拥有丰富的关联。联接模型(UsersProject)有一个额外的布尔属性administrator,它将User标记为Project的管理员:

当然,我在这里遗漏了一些明显的东西,但在创建新项目时,是否有一种干净的方法可以在连接模型(administrator)上设置UsersProject属性? e.g:

class Project < ActiveRecord::Base
  has_many :users_projects
  has_many :users, :through => :users_projects
end

class User < ActiveRecord::Base
  has_many :users_projects
  has_many :projects, :through => :users_projects

  # Guessing I use something along these lines, although should I be using scope?
  # has_many :administered_projects,
  #          :through => :users_projects,
  #          :source => :project,
  #          :conditions => ['users_projects.administrator = ?', true]
  #          ...
end

class UsersProject < ActiveRecord::Base
  # Join model has an boolean attribute :administrator
  belongs_to :user
  belongs_to :project
end

# INTENDED USAGE:

@project = @user.administered_projects.new(params[:project])
# => Creates a UsersProject record with `:administrator=true`

@project = @user.projects.new(params[:project])
# => Creates a UsersProject record with `:administrator=false`

感谢任何帮助, 克里斯

1 个答案:

答案 0 :(得分:1)

虽然没有直接回答你的问题,但实施对我来说似乎有些笨拙。

如果您有用户和项目,答案很简单 - 您可以在两个模型之间创建has_and_belongs_to_many关系,并创建连接表。管理员标志使情况稍微棘手,但我不确定是否需要加入模型

就个人而言,我只是在模型之间建立两种关系,如:

class Project < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_and_belongs_to_many :administrators, :class_name => 'User', :join_table => 'administrators_projects' # potentially some foreign_key directives here as well
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :projects
  has_and_belongs_to_many :administered_projects, :class_name => 'Project', :join_table => 'administrators_projects' # potentially some foreign_key directives here as well
end

这样,您仍然只拥有两个模型,但具有您需要的所有功能(并且您的“预期使用”结构将起作用)。如果你愿意,你也可以将管理员添加到projects_users关系中(这样管理员既是管理员又是用户),但这完全取决于你想要如何构建其余的表