Faisal Khurshid
Faisal Khurshid

Reputation: 1909

Rails form_tag not displaying the existing field value

I've a settings controller setup like this:

class Admin::SettingsController < ApplicationController

  def index
    @settings = Setting.all
  end

  def update
    setting_params.each do |key, value|
        Setting.where(key: key).first.update_attribute :value, value
    end

    redirect_to admin_settings_path, notice: "Settings saved."
  end

  private

  def setting_params
    params.require(:settings).permit(:site_title, :site_desc)
  end

end

The index action has a view file in relevant path, its code is as follows:

<h1>Settings</h1>

<%= form_tag admin_settings_path, method: "put" do %>

    <p>
        <label>Site Title:</label>
        <%= text_field_tag "settings[site_title]" %>
    </p>

    <p>
        <label>Site Description:</label>
        <%= text_field_tag "settings[site_desc]" %>
    </p>

    <p>
        <%= submit_tag "Save settings" %>
    </p>

<% end %>

Now, I'm able to save/update these fields data in relevant model and I can see the data through command Setting.all in rails console. But the issue is, after saving the record via form when I reload the settings index page the form is blank and it is not showing previously saved values in the fields.

What I'm doing wrong here?

Upvotes: 2

Views: 1952

Answers (2)

VPaul
VPaul

Reputation: 1013

You can do what has been mentioned in the previous answer i.e. using a form_for. However, this can also be accomplished by creating a Hash in both the controller actions that creates and processes this form.

In the action that creates this form, the values in the hash could be initialized to blanks/zeros depending upon the input tag and in the action that processes this form, the values in the hash could be assigned to the values obtained from the posted params[].

I ran into the similar issue with form_tag and I used the following code in my index action i.e. the action that renders the form initially:

@search = {name: "", ranking_group: 0}

Whereas, in the search action, I used the following code to fill up this hash:

@search = {name: params[:name], ranking_group: params[:ranking_group]}

Finally, in the view, I used the appropriate default value options with the input tags as below:

<%= text_field_tag :name, @search[:name] %>

<%= select_tag :ranking_group, options_for_select(AmenityEntities::Amenity.ranking_group_options, @search[:ranking_group]), include_blank: true %>

Hope this helps.

Upvotes: 1

Carlos Orellana
Carlos Orellana

Reputation: 184

I think you need to use form_for(@variable) instead of just a form_tag because you need to persiste the object after save.

form_for works with resources, take a look here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html

Upvotes: 0

Related Questions