Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails query related tables column value

In django you can create queries that span relationships

Entry.objects.filter(blog__name='Beatles Blog')

What is the rails equivalent?

like image 453
user2954587 Avatar asked Nov 27 '25 13:11

user2954587


1 Answers

Rails approach is not as clean, but it allows you to be explicit in your query. In a situation as described above, you would do

Entry.joins(:blog).where(blogs: {name: "Beatles Blog"})

This is assuming your Blog has_many :entries and your Entry belongs_to :blog

Also note that you still have access to a kind of SQL interface for this, however, you should always ensure to joins|includes|eager_load the associations that you would be querying, the way I joined the blog above.

Entry.joins(:blog).where("blogs.name = ?", "Beatles Blog")

OR using named parameters

Entry.joins(:blog).where("blogs.name = :blog_name", blog_name: "Beatles Blog")

Hope I was able to help.

like image 99
oreoluwa Avatar answered Nov 30 '25 03:11

oreoluwa