Reputation: 13407
I'm new to this, and I'm using datamapper and sinatra to build a basic app. I have a settings page with a few text inputs for several different settings.
This page, when viewed, should pull the information from the database and populate the input boxes if they're there.
For my Setting class I have :name and :value
As of right now, I have the code working which allows a setting to be created if the name doesnt already exist, and it updates it otherwise.
Setting.first_or_create(:name => "seed").update(:name => "seed", :value => params[:seed])
3 problems:
if the input is blank (after the first time obviously), it overwrites it with ""
How can I shorten this code down? In a 'real' ruby program, should i define a method so theres not so much redundant code? I have 5 settings so i feel having that line of code 5 times with only a few things different is kind of poor. The difficulty is that I would be forced to name="" all my inputs the exact hash that i'm using. Im not sure if thats poor practice or not, or whether I should just do it all explicitly 5 times
In order to 'get' the data to display it i have this:
@seed = Setting.get(:name => "seed")
That obviously doesn't work... what I need is to get params[:value] WHERE :name => "seed" and the use <%= @seed(???) %> to print it out. im not sure how to do this
Upvotes: 0
Views: 625
Reputation: 27747
@seed = Setting.first_or_create(:name => "seed") # fetch and store
# update only if there was one
@seed.update(:name => "seed", :value => params[:seed]) if params[:seed].present?
<!-- show the value in the page -->
<%= @seed.value %>
Upvotes: 1