Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to not repeat Rails ActiveRecord where condition arguments?

I have a Rails ActiveRecord where that looks like this:

Things.where('blahs.foo_id = ? OR bar_id = ?', user.id, user.id)

I want user.id to be used in place of the two ?'s. Is there a way to not repeat it like I've done?

like image 383
XåpplI'-I0llwlg'I - Avatar asked Aug 27 '13 04:08

XåpplI'-I0llwlg'I -


People also ask

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is ActiveRecord Query Interface in rails?

Active Record insulates you from the need to use SQL in most cases. Active Record will perform queries on the database for you and is compatible with most database systems, including MySQL, MariaDB, PostgreSQL, and SQLite.

What does where return rails?

where returns an ActiveRecord::Relation (not an array, even though it behaves much like one), which is a collection of model objects. If nothing matches the conditions, it simply returns an empty relation. find (and its related dynamic find_by_columnname methods) returns a single model object.

What happens on Save rails?

The purpose of this distinction is that with save! , you are able to catch errors in your controller using the standard ruby facilities for doing so, while save enables you to do the same using standard if-clauses.


1 Answers

Yes, just use a hash instead of repeat variables.

Things.where('blahs.foo_id = :user_id OR bar_id = :user_id', :user_id => user.id)
like image 166
Bigxiang Avatar answered Oct 22 '22 13:10

Bigxiang