开发者

Need to return all users with genre 'Acoustic'

Is there a better way to write this:

User.where(:genre_id => Genre.where(:name => 'Acoustic').first.id).first开发者_开发技巧.first_name

Basically, I am trying to return all users with genre 'Acoustic'.

Above will work if there are users with the Acoustic setting. But if i do:

User.where(:genre_id => Genre.where(:name => 'Pop').first.id).first.first_name

I will get an error, since there are no users associated with the pop genre...

Any suggestions to get this to work?


In a general way, many-to-many relationships really suck in mongo (the price you pay for has_one/has_many being so awesome)

I am assuming the problem is that Genre.where(:name => 'Pop').first returns nil? I would do this

User.where(:genre_id => g).first.first_name if g = Genre.where(:name => 'Pop').first.try(:id)

or if massive one line expressions aren't your thing

g = Genre.where(:name => 'Pop').first.try(:id)
if g
  User.where(:genre_id => g).first.first_name 
end


Doesn't the usual nested where work?

User.where(:genre => { :name => 'Pop' })


You could try with find instead of where for Genre:

User.where(:genre_id => Genre.find(:first, :conditions => { :name => 'Pop' }))

This should work even when Genre.find returns nil.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜