Cameron Cameron - 18 days ago 9
Ruby Question

Form field per table row in Rails

I have a settings table in my Rails app that has the following columns:

id, name, value


An example of some sample data might be:

id: 1,
name: 'site_name'
value: 'Cameron'

id: 2
name: 'email'
value: 'cameron@example.com'


What I want to do is have a page where I list these settings as simple text fields that I can then edit and save back into the database.

I have the following controller method that lists them:

def index
@settings = Setting.all
end


And then display them in the view like so:

<% @settings.each do |setting| %>
<div class="form__group">
<label class="form__group__label"><%= setting.name %></label>
<div class="form__group__input">
<input type="text" name="setting[<%= setting.name %>]" value="<%= setting.value %>">
</div>
</div>
<% end %>


Which displays them fine. But how do I save them?

I was thinking about looping through them in the controller like:

def update_settings
params[:setting].each do |setting|
# somehow update each param sent back...
end
end

Answer

Your update action should look like

def update_settings
  params[:setting].each do |setting|
    setting_row = Setting.where(name: setting.first).first_or_initialize
    setting_row.update(value: seting.last)
  end
end

I'm using .first_or_initialize method for possible use case when Setting with that name does not exist.

Comments