开发者

Rails 3: Many-to-Many relation with condition

开发者 https://www.devze.com 2023-02-11 13:06 出处:网络
I have the following models class Project < ActiveRecord::Base has_many :project_members has_many :members, :through => :project_members, :uniq => true,:class_name => \"User\",:source =&

I have the following models

class Project < ActiveRecord::Base
  has_many :project_members
  has_many :members, :through => :project_members, :uniq => true,:class_name => "User",  :source => :user
  has_many :admins, :through => :project_members, :uniq => true, :conditions => ['project_members.admin = ?', true], :class_name => "User", :source => :user

end

class User < ActiveRecord::Base
  # References
  has_many :project_members
  has_many :projects, :through => :project_members

end

and the join table

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

The relations seem to work, but when I want to add an admin to a project via this code

project.admins.push(u)
project.save

(where u is a User) it saves the new relationship but without setting admin to true in the join table.

Even if I retrieve this relation from the project and setting admin to true manually by doing

project.project_members.first.admin = true

and saving the project it doens't update the attribute in the table.

What am I doing wrong? (Please keep in mind that 开发者_Go百科I'm a total beginner with ruby and rails)

I have been googling for the last hours to find a solution but couldn't find anything :/


I think you have to change your admins association to :

has_many :admins, :through => :project_members, :uniq => true, :conditions => {:project_members => {:admin => true}}, :class_name => "User", :source => :user

I hope that will help you.

0

精彩评论

暂无评论...
验证码 换一张
取 消