尝试从连接模型中读取属性时不会出现方法错误

我有项目和用户通过has_many加入:通过称为所有权的连接模型。 每个所有权都有我要访问的owner_type属性。

我想有办法将user_id传递给项目模型,并通过所有权连接模型获取owner_type。 反之亦然我想将project_id传递给用户模型并通过所有权连接模型获取owner_type。 这是我有的:

class Project  :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  :ownerships accepts_nested_attributes_for :projects email_regex = /\A[\w+\-.]+@[az\d\-.]+\.[az]+\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  true validates :project_id, :presence => true validates :owner_type, :presence => true end 

然后在我的项目#show页面中:

  

我究竟做错了什么? 如何从任何地方访问所有权模型中的owner_type属性? 它永远不会奏效。

你还没有粘贴你得到的实际错误。 但这是我认为出了问题。

ownerships是一种非常多的关系。 它将始终返回结果集合。 因此, @ownership = self.ownerships.where(:user_id => @user_id)将返回一个数组。 所以,如果您只期望1个结果,那么您应该这样做。

 @ownership = ownerships.where(:user_id => @user_id).first @ownership.owner_type 

这应该工作。