Rails 关于 ruby-china 收藏的一句代码!

stephen · 2012年01月14日 · 最后由 richfisher 回复于 2012年02月04日 · 2130 次阅读
Like.find_or_create_by(:likeable_id => likeable.id, 
                           :likeable_type => likeable.class,
                           :user_id => self.id)

这里的 find_or_create_by 为什么我这样写就会输出 undefined method find_or_create_by错误,我换了一种方法,例如

Like.find_by_likeable_id_and_likeable_type_or_create()

也出错, 我发现,只要加上_or_create 就会出错,是不是我缺少了什么东西? rails 3.1

这是 mongoid 的方法 http://mongoid.org/docs/querying/finders.html#find_or_create_by 找不到这个方法,又没有代码,只有你自己检查自己的环境配好了没有

@cqpx 哦,我也想到是 mongoid 的方法,我是用 activerecord 的,没类似的魔法方法?gg 搜不到!

#2 楼 @stephen activerecord 也有这个方法,叫 Dynamic attribute-based finders http://api.rubyonrails.org/classes/ActiveRecord/Base.html

还是自己检查环境

AR 的用法,Model.find_or_create_by_field1_and_field2_and_field3(value1,value2,vaule3)

需要 登录 后方可回复, 如果你还没有账号请 注册新账号