问题描述
我有项目,用户可以通过的has_many加盟:通过加盟模式称为所有权。每个所有权的拥有,我要访问一个owner_type属性。
I have projects and users joined via has_many :through join model called ownerships. Each ownership has an owner_type attribute that I want to access.
我希望有一种方式来传递一个user_ID的一个项目模型,并得到通过所有权owner_type加盟模式。反之亦然我想通过一个PROJECT_ID到用户模式并获得通过所有权owner_type加盟模式。以下是我有:
I want to have a way to pass a user_id to a project model and get the owner_type via the ownership join model. And visa versa I want to pass a project_id to a user model and get the owner_type via the ownership join model. Here is what I have:
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
,然后在我的项目#显示页面:
and then in my project#show page:
<%= @project.owner_type?(current_user.id) %>
我是什么做错了吗?如何从任何地方访问从所有制模式的owner_type属性?它从来就行不通。
what am I doing wrong? How do I access the owner_type attribute from the ownership model from anywhere? It never works.
推荐答案
您还没有粘贴你所得到的实际误差。但在这里就是我的想法是怎么了。
You haven't pasted the actual error you are getting. But here is what I think is going wrong.
所有权
是的has_many
的关系。它会回报你的结果集合,始终。因此, @ownership = self.ownerships.where(:USER_ID =&GT; @user_id)
将回报你一个数组。所以,如果你希望只有1结果你应该做的事情。
ownerships
is a has_many
relationship. It will return you a collection of results, always. Thus, @ownership = self.ownerships.where(:user_id => @user_id)
will return you an array. So you should probably be doing if you expect only 1 result.
@ownership = ownerships.where(:user_id => @user_id).first
@ownership.owner_type
这应该工作。
这篇关于试图读取属性从加盟模式时,没有得到方法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!