1

Is there a special way that you should call an object when you want to add a where clause that relates to a relationship that has been defined in the model.

An example would be that I have an image, the image belongs_to or has_many (whatever rocks your boat) a category, and I want to select all images that don't have any associated categories.

So for a simple belongs_to I could just say:

Image.where('category_id is null')

But is there a better way of doing this since the relationship has been explicitly defined in the model?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Rumpleteaser
  • 4,142
  • 6
  • 39
  • 52

2 Answers2

0

Are you feeling uncomfortable using where with a string clause? I have that feeling everytime I use where.

You can also do

Image.where(:category_id=>nil)

or use the dynamic finder method

Image.find_all_by_category_id(nil)

or load via the association @images = Category.find(some_cat_id).images

(This one doesn't work for nil)

I think all of them should generate more or less the same SQL.

Damon Aw
  • 4,722
  • 4
  • 28
  • 37
  • Its not that i feel uncomfortable using string clauses, its just that the models are all there so it makes sense for there to reference the relationship itself rather than resorting to referencing the database itself. it kind of negates the point of the model – Rumpleteaser Mar 01 '12 at 08:39
  • Sorry for the bad phrasing. I'm uncomfortable using "strings" because I feel that there shouldn't be a need to write any queries. should all be done by the model's association itself. – Damon Aw Mar 01 '12 at 12:27
0

Try this:

Image.find(:all, :conditions => 'category_id is null')
Anthony
  • 12,177
  • 9
  • 69
  • 105
dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58