开发者

named_scope dependent on existence of association is breaking tests

User model:

class User < ActiveRecord::Base
  named_scope :clients, 
    :conditions => "roles_users.role_id = #{Role.find_by_name('client').id}"
end

When testing, throws error:

Called id for nil, which would mistakenly开发者_如何学JAVA be 4 -- if you really wanted (etc.)

Role fixtures:

client:
  name: client
user:
  name: user

Apparent problem: Rails is loading this class before it loads fixtures. When it loads the class it evaluates the named_scope. There are no roles at that point, so it blows up.

Possible solution:

named_scope :clients, 
  lambda { { :conditions => "roles_users.role_id = #{Role.named('client').id}" } }

However, I am not pleased with this solution, seeing as it introduces additional complexity and presumably a (small?) performance hit, just so that tests run properly. I'd like an alternative. Can you help?


The solution you propose is the correct solution. I would also recommend changing your code to:

named_scope :clients, lambda { { :conditions => ['roles_users.role_id = ?', Role.named('client').id } }

An alternative might be:

named_scope :clients, :joins => :role, :conditions => ['roles.name = ?', 'client']

You might also want to think about doing:

named_scope :with_role, lambda { |r| { :conditions => ['roles_users.role_id = ?', r.id] } }

Or even (for extra points)

Role.find_by_name('client').users

Anyway, I hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜