views:

35

answers:

2

Basically, I want an array of ids from the database.

Some background:

  • I'm rendering a list of objets (foos) to the user with a checkbox.
  • If the user checks the box a row is create in a different table (bar)
  • when rendering the foo list + checkbox I want to check if the unique id any given foo already exists in the bar id array.

I assumed that getting an array of ids would be much more efficient than querying the database for each instance of foo when rendering the foo list with checkboxes.

Ideas? Apologies in advance if this is not clear.

A: 

What's the problem, than? If you have rails has_many or has_and_belongs_to_many association, rails will fetch ids for you. See relevant tutorial for details, in short it's like @order_ids = @customer.order_ids.

Otherwise, you can easily use plain sql (or active record query).

Nikita Rybak
I am aware of has_many,etc. But again, you're making an association query for each foo, that doesn't seem as efficient as pre-fetching all the bar ids and then comparing.
cbrulak
@cbrulak When you invoke 'order_ids', rails don't run query for each result. And again, you can always switch to sql: "select id from my_table where ...".
Nikita Rybak
A: 

I used the map method:

@bars = Bar.all(:select => bar.id)
@bars = @bars.map{|bar| bar.id}

Then I end up with array of ids. And only one query.

cbrulak