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
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.