我的理解是,你可以在任何模型上执行这样的SQL查询,它会返回数据作为该模型的实例。请阅读find_by_sql。这是来自文档的示例。请注意,是返回一个Post对象:
Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
Rails 3的查询语法应该给你所有你需要拿到虽然此信息。我会尽可能避免使用原始SQL,您可以非常快速地将它绑定到特定的数据库。看看here获得一些灵感。
传递PARAMS到的find_by_sql可以这样做:
irb(main):015:0> y Location.find_by_sql(["select address, name from locations where name = :name and address = :address", {:address => "Arts Court 2 Daly Ave, Ottawa, ON", :name => "Studio B"}])
---
- !ruby/object:Location
attributes:
name: Studio B
address: Arts Court 2 Daly Ave, Ottawa, ON
attributes_cache: {}
changed_attributes: {}
destroyed: false
marked_for_destruction: false
new_record: false
previously_changed: {}
谢谢,我怎么能传递两个或更多PARAMS到的find_by_sql方法? – 2011-04-02 15:22:19
解决Question.find_by_sql([sql,'2011-04-06',1]) – 2011-04-02 15:52:48
我给我的答案添加了一个例子。 – mikewilliamson 2011-04-02 16:05:25