Cameron Cameron - 8 months ago 46
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: ''

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

And then display them in the view like so:

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


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)

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