Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
Converting sql query to ruby on rails query
6 Posts
Converting sql query to ruby on rails query

Hi there,

I'm trying to create a query in rails for showing specific content. You can find the sql in the pastie. But how can I implement this in rails?

I've been trying the ruby code from the pastie But I'm having problems with my brackets.

Does anyone see what's wrong?

http://pastie.org/380566

I think that you need to use other brackets like:

Page.all :conditions => ["parent_id is null and content_id <> '' and category_id = ?", params[:id]]

Is it safer to use this category_id = ?”, params[:id]] or find_all_by_category_id(params[:id])?

It's not safer, just some people prefer using the dynamic helpers.

Something else you should look at is named_scope. This let's you embed this sort of static condition in your model where it belongs.

I'm on my iphone so I can't test this (tested now) but you would add something like this to your model:

named_scope :top_dutch, :conditions => "parent_id is null and dutch_content &lt;> ''"

I think you should then be able to do something like:

Page.top_dutch.find_all_by_page_category_id(4)

Check the API and test, sorry this is untested (tested now).

Edit: tested now, works as I suggested.

Thanks Jason for your answer it works fine indeed!

Happy to help, named_scope is an awesome feature for moving this sort of business logic back into the model.

6 Posts
Login to add your message