Custom SQL query without Corresponding Table

后端 未结 3 842
遇见更好的自我
遇见更好的自我 2021-01-30 14:55

I have a SQL query that isn\'t table-specific and I don\'t know how to handle it with Ruby On Rails.

Here my SQL query (you don\'t need to understand it):

SELE         


        
相关标签:
3条回答
  • 2021-01-30 15:27

    You can also grab the ActiveRecord connection and call select_all:

    ActiveRecord::Base.connection.select_all('select * from foo').each do |e|
      puts e.inspect
    end
    
    0 讨论(0)
  • 2021-01-30 15:34

    You can grab a db connection directly from ActiveRecord::Base, but it's not as useful as extending AR::Base, because helpful methods like sanitize_sql are protected.

    class ComplexQueries < ActiveRecord::Base
      def self.my_query
        # Notice how you can, and should, still sanitize params here. 
        self.connection.execute(sanitize_sql(["select * from foo limit ?", 10]))
      end
    end
    
    results = ComplexQueries.my_query
    results.each_hash{|h| puts h.inspect}
    
    0 讨论(0)
  • 2021-01-30 15:36

    If you want to create classes (models) that are not backing to a database you need to not state that they are inheriting from ActiveRecord.

    Do

    class RecentActivity
    

    Instead of

    class RecentActivity < ActiveRecord::Base
    

    That being said, it still might be helpful to get some more information on what you are trying to do: for example if you want to have something like "comments" or "pictures" on multiple different things like an article, or someones profile or blogpost all within the same application, I'd recommend checking out PolyMorphic Associations.

    0 讨论(0)
提交回复
热议问题