Merge Nested Attributes

2019-07-08 09:35发布

问题:

I have a sample using post, comments and author models. Please see my full requirement from the following thread

Nested routes and CRUD operations with additional values for assciation in Rails

Here i need to create one comment when a post is created. I used nested attributes and working fine. But my issue is i don't want all attributes from the user. Some attributes needs to be added internally. I can merge if the attributes not having nested attributes. But merge not worked for nested attributes.

I got a solution from here

Now my params method is like below;

private

def create_params
filtered_params = params.require(:post)
                        .permit([:name, 
                                 :description, 
                                 comments_attributes: [:author_id, :comments]])

additional_params = {record_status: 1, comments_attributes: [record_status: 1]}

result = filtered_params.merge(additional_params) do |key, oldval, newval|
  if newval.is_a? Array
   oldval ||= {}
    Hash[oldval.map {|k, v| [k, v.merge(newval.first)]}]
  elsif newval.is_a? Hash
    oldval ||= {}
    oldval.merge newval
  else
    newval
  end
end

result.permit!

end

and my create method is ;

def create

 @post = Post.new(create_params)

  if @post.save 
   render :show, status: :created
  end
 end

But i got error in merge methods like below;

Started POST "/api/posts" for 127.0.0.1 at 2015-08-06 06:47:08 +0530 Processing by Api::PostsController#create as JSON Parameters: {"post"=>{"name"=>"post 11", "description"=>"desc", "comments_attributes"=>[{"author_id"=>1, "comments"=>"my new .............. Completed 500 Internal Server Error in 12ms (ActiveRecord: 0.0ms)

NoMethodError (undefined method merge' for nil:NilClass):
app/controllers/api/posts_controller.rb:40:in
block (2 levels) in create_params' app/controllers/api/posts_controller.rb:40:in map'
app/controllers/api/posts_controller.rb:40:in
block in create_params' app/controllers/api/posts_controller.rb:31:in create_params'
app/controllers/api/posts_controller.rb:10:in
create'

When i use logger i can understand that error got from the below line. (v is Nil)

   oldval ||= {}
    Hash[oldval.map {|k, v| [k, v.merge(newval.first)]}]

Please help me to solve this issue