English 中文(简体)
Rails Custom Model Functions
原标题:

I m in a databases course and the instructor wants us to develop an e-commerce app. She said we can use any framework we like, and now that we re halfway through the semester she decided that Rails does too much and wants me to explicitly write my SQL queries.

So, what I d like to do is to write my own functions and add them to the models to essentially duplicate already existing functionality (but with SQL that I wrote myself).

So the questions then become:

  1. How do I execute manually created queries inside the model?
  2. How do I stuff the results into an empty object that I can then return and work with inside the view?

Also, I m aware of what terrible practice this is, I just don t want to start all over in PHP at this point.

最佳回答

I think, you should know 2-3 really necessary methods, to use it. (assume we have at least 2 models, Order and User(customer for order)) For example, just to run query on your database use this:

Order.connection.execute("DELETE FROM orders WHERE id =  2 )

to get number of objects from your database, the best way is use method "count_by_sql", it s scalable. I m using it in my projects, where table has over 500 thousands records. All work to count application gives to database, and it did it much more efficient than app.

Order.count_by_sql("SELECT COUNT(DISTINCT o.user_id) FROM orders o")

this query gets number of all uniq users who has an order. we can "JOIN ON" tables, order results using "ORDER BY" and group results.

and the most often use method: find_by_sql

Order.find_by_sql("SELECT * FROM orders")

it returns to you an array with ruby objects.

问题回答

Lets say you have a purchase

class Purchase < ActiveRecord:Base
    def Purchase.find(id)
        Purchase.find_by_sql(["Select * from purchases where id=?", id])
    end  
end 

Maybe you want the products for a particular purchase. You can manually define the purchased_items in your Purchase model.

class Purchase < ActiveRecord:Base
    def purchased_items
        PurchasedItem.find_by_sql(["Select * from purchased_items where purchase_id=?",self.id])
    end
end

So for example, in your controller where you now want to get the purchased items for a particular purchase you can now do this

@purchase = Purchase.find(params[:id])
@purchased_items = @purchase.purchased_items

If you need a more raw connection to the database, you can look into ActiveRecord:Base.connection.execute(sql)





相关问题
rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

SSL slowness in EC2

We ve deployed our rails app to EC2. In our setup, we have two proxies on small instances behind round-robin DNS. These run nginx load balancers for a dynamically growing and shrinking farm of web ...

Auth-code with A-Za-z0-9 to use in an URL parameter

As part of a web application I need an auth-code to pass as a URL parameter. I am currently using (in Rails) : Digest::SHA1.hexdigest((object_id + rand(255)).to_s) Which provides long strings like : ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

activerecord has_many :through find with one sql call

I have a these 3 models: class User < ActiveRecord::Base has_many :permissions, :dependent => :destroy has_many :roles, :through => :permissions end class Permission < ActiveRecord::...

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

How to get SQL queries for each user where env is production

I’m developing an application dedicated to generate statistical reports, I would like that user after saving their stat report they save sql queries too. To do that I wrote the following module: ...

热门标签