P
P
Pavel Grudinkin2016-03-24 03:06:26
Ruby on Rails
Pavel Grudinkin, 2016-03-24 03:06:26

How to merge two activerecord objects?

For example, in the database we have a table with comments, we pulled out several related to one post from the database, and pulled out a few more related to another post. How to merge these two objects? Is it possible to do this in string concatenation style?
I will describe the task more specifically:
There is a store that has many addresses, comments (reviews) are written to the addresses. Next, you need to get all the confirmed records. Tried to do like this:
@addresses = Address.where(shop_id: @shop.id)

@addresses.each do |addr|
      @comments = addr.comments.confirmed
end

But of course this only works for one last address. Tried
@comments = Comment.new
@addresses.each do |addr|
      @comments = @comments.merge(addr.comments.confirmed)
end

, but
NoMethodError (undefined method `merge' for#<Comment:0x007ff493627ef8>):`

and
NoMethodError (undefined methodmerge' for nil:NilClass)
:`
if @comment = Comment.new
Update
class Comment < ActiveRecord::Base
  belongs_to :address
  scope :with_text, -> { where.not(:text => nil) }
  scope :confirmed, -> { where(:confirmed => true) }
  scope :starred, -> { where.not(:stars => nil) }

  def confirm!
    self.update_attributes(:confirmed => true)
  end
end

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vayladion Gognazdiak, 2016-03-24
@etspring

And if so
Address.where(shop_id: @shop.id).joins(:comments).confirmed ?

P
Pavel Grudinkin, 2016-03-27
@Hunt666

in my case everything turned out as described here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question