我有项目和用户通过has_many加入:通过称为所有权的连接模型。每个所有权都有我想要访问的owner_type属性。
我希望有办法将user_id传递给项目模型,并通过所有权连接模型获取owner_type。反之亦然我想将project_id传递给用户模型并通过所有权连接模型获取owner_type。这就是我所拥有的:
class Project < ActiveRecord::Base
attr_accessible :name, :description
has_many :ownerships
has_many :users, :through => :ownerships
validates :name, :presence => true,
:length => { :maximum => 50 }
def owner_type?(user_id)
@user_id = user_id
@ownership = self.ownerships.where(:user_id => @user_id)
@ownership.owner_type
end
end
class User < ActiveRecord::Base
attr_accessible :name, :email, :admin
has_many :ownerships
has_many :projects, :through => :ownerships
accepts_nested_attributes_for :projects
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 50 }
#validates :email, :presence => true,
# :format => { :with => email_regex },
# :uniqueness => { :case_sensitive => false }
validates_inclusion_of :admin, :in => [true, false]
def self.create_with_omniauth(auth)
create! do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
user.name = auth["user_info"]["name"]
user.admin = false
end
end
end
class Ownership < ActiveRecord::Base
attr_accessible :owner_type
belongs_to :project
belongs_to :user
validates :user_id, :presence => true
validates :project_id, :presence => true
validates :owner_type, :presence => true
end
然后在我的项目#show page:
<%= @project.owner_type?(current_user.id) %>
我做错了什么?如何从任何位置访问所有权模型中的owner_type属性?它永远不会奏效。
答案 0 :(得分:1)
您尚未粘贴实际的错误。但这就是我认为出了问题。
ownerships
是一种has_many
关系。它将始终返回一组结果。因此,@ownership = self.ownerships.where(:user_id => @user_id)
将返回一个数组。因此,如果您只期望1个结果,那么您应该这样做。
@ownership = ownerships.where(:user_id => @user_id).first
@ownership.owner_type
这应该有用。