Rails, Why a ActiveRecord Query works in a controller but not a Helper?
I have the following line of Rails 3
In the project.rb model this works great:
permissions.find_by_project_id(1).role.name
However in a projects_helper it errors "undefined method `role' for nil:NilClass":
if Permission.find_by_project_id(project_id).role.name.nil?
.
.
Why is that?
What I really want is:
current_user.permission.find_by_project_id(project_id).role.name.nil?
But that errors: "undefined method `permission' for #"
Can you help me understand ActiveRecord allowing me to build these queries?
Thanks
added info:
p开发者_StackOverflow中文版ermission.rb
class Permission < ActiveRecord::Base
belongs_to :user
belongs_to :project
belongs_to :role
end
project.rb
class Project < ActiveRecord::Base
has_many :permissions
has_many :users, :through => :permissions
end
role.rb
class Role < ActiveRecord::Base
has_many :permissions
end
user.rb
class User < ActiveRecord::Base
belongs_to :instance
has_many :books
has_many :permissions
has_many :projects, :through => :permissions
It looks like role
is not set for the given project. You can work around it by:
current_user.permissions.find_by_project_id(project_id).role.try(:name).nil?
There must be a more elegant way to write this, so feel free to suggest improvements. The point is that you have to check first that project
is not nil
before you can do something with project.role
.
def team_member?(project_id, current_user)
project = current_user.permissions.find_by_project_id(project_id)
if !project.nil? && !project.role.nil?
# your code
else
# return false?
end
end
精彩评论