Set attr_accessor value on ActiveRecord Relation

1.6k Views Asked by At

I have an ActiveRecord Relation from which I would like to set an attribute not persisted. Unfortunately, it is not working.

I think the best way of seeing the problem is just seeing the code:

class Post < ActiveRecord::Base
  attr_accessor :search
end

In my controller I have:

results.where(id: search_posts).each do |result_out_of_search|
  result_out_of_search.search = true
end
results.where(id: search_posts).first.search #returns nil

Thanks in advance

2

There are 2 best solutions below

0
Shadwell On BEST ANSWER

The reason you're not seeing your search attributes as true is because you are fetching the posts again wit the second call. As you say, the attribute is not persisted so you need to ensure that you are working with the same collection of posts. If you run your code in the console, or look at the logs from the server, you'll see the query to fetch posts being run twice.

To ensure you're using the same collection you need to keep track of it explicitly rather than doing results.where(...) again:

posts = results.where(id: search_posts)
posts.each do |result_out_of_search|
  result_out_of_search.search = true
end
posts.first.search # Should be true

If you are just decorating search results you may also get some value from a gem like draper which encapsulates that idea quite nicely.

0
Raza On

Try this

results = results.where(id: search_posts)

results.each do |result_out_of_search|
  result_out_of_search.search = true
end

results.first.search

You need to load the records to the memory first. As results.where(id: search_posts) results in a db query, it is not what u want. You need to load to the memory, and then retrieve it from the memory.