0

I am getting undefined method #merge however #merge method works good in the second block. What's wrong with Block 1?

# Block 1
network_posts = []
@networks.each do |network|
  network_posts << network.posts.as_json.merge('pic' => network.pic.url) 
end
# Block 2
network = []
@networks.each do |network|
  network << network.as_json.merge('pic' => network.pic.url) 
end

1 Answer 1

2

The as_json method is not obligated to return a Hash. It can return anything it wants, a string, a number, a boolean value, or even, as in this case, an array. Assuming it supports merge is a mistake.

Since this appears to be operating on a collection (network.posts) that will be an array. Merging that in isn't practical. You could merge in on each record's as_json result:

network.posts.map do |post|
   post.as_json.merge(...)
end
Sign up to request clarification or add additional context in comments.

2 Comments

hey, but your code inside merge part is missing, how should it fetch network.pic.url if you map it by |post|
It'll work just the same as network is valid in that context. It's only removed for brevity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.