Search code examples
ruby-on-railsformsformtastic

rails forms updating a db record


I would like to rewrite a form which is used to update a record on a database. I want to update the form so that the form input does not show the record, as the record is outputted by the line

<%= q.object.content %>. 

I want the form input not to display the record, and I want that the record is updated when the input field is edited, and is not edited when it is left blank.

I am new at working with forms and don't know the best way to achieve this.

Can anyone provide any help on achieving this ? Below is the current form. Any help would be appreciated.

<%= semantic_form_for @bunchOfThings do |f| %>
    <%= f.inputs do %>
        <%= f.semantic_fields_for :aThing, @aThing do |q| %>
            <%= q.object.content %> 
            <%= q.input :content, label: "A Thing: #{q.object.content}" %>
        <% end %>
    <% end %>
    <%= f.action :submit , label: t('Some Text'), button_html: { class: 'btn btn-primary' } %>
<% end %>

Solution

  • You can manually set the default value of a field to an empty string by changing this line:

    <%= q.input :content, label: "A Thing: #{q.object.content}" %>
    

    To this:

    <%= q.input :content, label: "A Thing: #{q.object.content}", input_html: {value:''} %>
    

    You would also need to filter out blank fields on the backend within the update controller method. Something like this:

    def update
      filtered_params = permitted_record_params
      filtered_params.keep_if{|k,v| !v.blank? }
      record.update(filtered_params)
      ...
    end
    

    Where of course the permitted_record_params method returns your permitted params hash.