gpt4 book ai didi

ruby-on-rails-3 - Rails 3 has_many :through + join table conditions/scoping

转载 作者:行者123 更新时间:2023-12-04 03:34:01 25 4
gpt4 key购买 nike

我正在开发一个模型为UserProject的应用程序,并且可以通过UserProject分配给多个ProjectUser s,并具有一个角色(例如Developer,Designer)。

Project
has_many :project_users
has_many :users, :through => :project_users

User
has_many :project_users
has_many :projects, :through => :project_users

ProjectUser (user_id, project_id, role)
belongs_to :user
belongs_to :project

我可以调用 @project.users@user.projects,但是由于角色不同,因此我想更具体地说明这种关系。理想情况下,我希望能够执行以下操作:
@project.developers
# returns @project.users, but only where ProjectUser.role = 'Developer'

@project.designers << @user
# creates a ProjectUser for @project, @user with role 'Designer'

@user.development_projects
# returns projects where @user is assigned as a 'Developer'

@user.design_projects << @project
# creates a ProjectUser for @project, @user with role 'Designer'

我目前有以下代码:
has_many :developers, :through => :project_users, :source => :user,
:class_name => "User",
:conditions => ['project_users.role = ?','Developer']

但是,这实际上仅是单向获取,并没有给我太多其他好处-我无法构建或分配或执行任何操作。

我正在尝试一些更复杂的逻辑,这些逻辑我认为可能有用,但希望能获得一些指导:
has_many :developer_assignments, :source => :project_user,
:conditions => { :role => 'Developer' }
has_many :developers, :through => :developer_assignments # class_name?

有什么建议么?谢谢!

最佳答案

has_many接受一个可以定义/覆盖关联方法的块。这将允许您为<<创建一个自定义方法。我为您创建了一个小示例,您可以用类似的方式创建构建。

# Project.rb
has_many :developers, :through => :project_users, :source => :user,
:conditions => "project_users.role = 'developer'" do
def <<(developer)
proxy_owner.project_users.create(:role => 'developer', :user => developer)
end
end

现在,您可以使用以下命令将新的开发人员添加到您的项目中: @project.developers << @user@project.developers为您提供了所有开发人员。

如果您有很多角色,则动态创建这些has_many语句可能会很有用。

# Project.rb
ROLES = ['developer','contractor']

ROLES.each do |role|
self.class_eval <<-eos
has_many :#{role.downcase}s, :through => :project_users, :source => :user,
:conditions => "project_users.role = '#{role}'" do
def <<(user)
proxy_owner.project_users.create(:role => '#{role}', :user => user)
end
end
eos
end

回顾上面的所有内容似乎都不是正确的工作方式。对此进行范围界定应该可以在不重新定义所有内容的情况下使构建和创建命令正常工作。

希望这可以帮助!

关于ruby-on-rails-3 - Rails 3 has_many :through + join table conditions/scoping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7753162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com