Home > Software engineering >  1 parameter not saving on create
1 parameter not saving on create

Time:11-01

I have a 'parent_id' which is successfully passed as parameter into a form page ("Create Child") here :

<li><%= link_to "Create Child", new_block_path(:parent_id => @block.id)%></li>

Logging the parameter gives :

Started GET "/blocks/new?parent_id=7" for ::1 at 2022-10-31 22:01:05  0000
Processing by BlocksController#new as HTML
  Parameters: {"parent_id"=>"7"}

I then have a form which calls a create method here :

def create
    @block = Block.new(block_params)

    if @block.save
      redirect_to @block
    else
      render :new, status: :unprocessable_entity
    end
  end

using these block_params

private 
    def block_params
      params.require(:block).permit(:title, :body, :parent_id)
    end
  end

But when I call the create function only :title and :body are present.

Printing the parameters shows :

Started POST "/blocks" for ::1 at 2022-10-31 22:01:17  0000
Processing by BlocksController#create as TURBO_STREAM
Parameters: {"authenticity_token"=>"[FILTERED]", 
"block"=>{"title"=>"this is a child of block 7", 
"body"=>"this is a child of block 7"}, "commit"=>"Create Block"}

Filtered shows :title and :body are permitted correctly, but the URL parameter of parent_id has just vanished.

The rails guide states : "Submitted form data is put into the params Hash, alongside captured route parameters" - I just can't work this out. The parent_id parameter is there as it should be when the form is loaded, but when submitted it vanishes.

CodePudding user response:

There are two actions, new and create, you could think they are separate.

So params from new won't be available in create automatically (in your case parent_id), you have to pass the params explicitly.

You could just add a hidden input in your form to pass parent_id:

<%= form_with model: @block do |f| %>
  <%= f.hidden_field :paren_id, value: params[:parent_id] %>
  <%= f.text_field :title %>
  <%= f.text_field :body %>
<% end %>

  • Related