lundi 27 avril 2015

How to fetch attribute value from database and apply to form

I am trying to get the background-color for forms from the user and storing the value in user_preference table and applying those back-ground color by fetching data from table into the same form.

My forms look like this:

<%= form_for @user_preference do |u|%>
 <p>
    <%= u.label :title %><br>
    <%= u.text_field :title %>
  </p>

  <p>
    <%= u.label :description %><br>
    <%= u.text_field :description %>
  </p>

  <p> <%= u.label :back_ground_color %><br>
    <%= u.select :bgcolor, options_for_select(UserPreference.bgcolor_options) %>
  </p>

  <p>
    <%= u.label :font %><br>
    <%= u.select :font, options_for_select(UserPreference.font_options) %>

  </p>

 <br >
  <p>
    <%= u.submit %>
  </p>
  <div style="<%= 'background-color:#{@user_preference.bgcolor};' %>"</style></div>
  <hr >
<% end %>

I am rendering this form again after saving the value in database, is this the way to do ?

here is my controller:

class UserPreferencesController < ApplicationController
    def new
        @user_preference = UserPreference.new
    end

    def create
        @user_preference = UserPreference.new(user_pref_params)
        @user_preference.user = current_user
        @user_preference.save if user_signed_in?
        render 'user_preferences/new'
    end

Is it the correct way of doing... let me know where I am doing mistake, any help will be appreciated.

Aucun commentaire:

Enregistrer un commentaire