开发者

Rails has_many with finder_sql and name_scope in combination return nil

开发者 https://www.devze.com 2023-04-11 17:03 出处:网络
For example lets say you have: class Model < AR::Base has_many :somethings, :finder_sql => \"SELECT * FROM somethings\"

For example lets say you have:

       class Model < AR::Base 
         has_many :somethings, :finder_sql => "SELECT * FROM somethings"
       end

       class Something < AR::Base
         named_scope :valuable {...code...}
       end

 开发者_如何学Python      # Assume you have one model but 0 somethings:  
       # Model.first.somethings          # => [] Good!
       # Model.first.somethings.valuable # => nil Bad! Should return [] !!!

This only occurs when you have finder_sql in has_many relationship. In other cases it works as expected.

Is this normal behavior of Rails 2.3.14?


yes, if you specify finder_sql, then you will not be able to append scopes. that's because finder_sql is for situations that do not fit the normal activeRecord paradigm. That being said, the way you have this constructed is incorrect. you should not need to store a select * with no filters in a relationship like that. the purpose of a relationship is to apply a filter to the other model. so, the way you have it Model.find(params[:id]).somethings is exactly the same as calling Something.all . the scope will work for you in the latter case because .all can be scoped.

0

精彩评论

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