slehmann36 slehmann36 -4 years ago 50
Ruby Question

Append an ActiveRecord::Relation object with single ActiveRecord object

I need to append a single ActiveRecord object onto a loaded ActiveRecord::Relation.

E.g:

class BooksController < ApplicationController
def index
@books = Book.where(author: User.find(params[:user_id]))
@books << Book.find_by_name("One More Book")
end
end


As shown above, I have tried ActiveRecord's
<<
method
, but it returns the error:

NoMethodError: undefined method `<<' for #<Book::ActiveRecord_Relation:0x007f9fbdc6db80>


Is there an elegant way of doing this?

Thanks!

Answer Source

As a temporary fix, I have done the following:

books = Book.where(author: User.find(params[:user_id])).pluck(:id)
books << Book.find_by_name("One More Book").id
@books = Book.where(id: books)

For obvious reasons, this is solution is far from ideal, but it does work while a better solution can be found.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download