【问题标题】:How to fetch attribute value from database and apply to form如何从数据库中获取属性值并应用于表单
【发布时间】:2015-04-23 10:01:28
【问题描述】:

我正在尝试从用户那里获取表单的背景颜色并将值存储在 user_preference 表中,并通过从表中获取数据到相同的表单中来应用这些背景颜色。

我的表单如下所示:

<%= 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 %>

我在将值保存到数据库后再次渲染此表单,这是这样做的吗?

这是我的控制器:

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

这是正确的做法吗... 让我知道我在哪里做错了,任何帮助将不胜感激。

【问题讨论】:

  • 您遇到错误了吗?显然@user_preference.bgcolor 将是一个新记录的空白,可能会给你一个错误。
  • 不,我没有收到任何错误,因为我在将值保存到数据库后呈现 new.html.erb。我不知道我的方法是否正确,如何实现?
  • 也许你应该让用户在提交表单之前先使用 js 预览更改。
  • @bodyfarmer 请告诉我检查预览的方法
  • 您想根据用户创建的最后一个 UserPreference 更改背景颜色吗?我同意@bodyfarmer:您应该让用户先预览更改

标签: css ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4


【解决方案1】:

如果您想获取最后一个数据并根据它更改背景颜色,那么您必须在呈现新表单时传递对象:

更改控制器的新方法(编辑:UserPreference 中的 FIXED Typo):

def new
  @user_preference = UserPreference.new
  @last_bgcolor = UserPreference.last.bgcolor #this will fetch the last data and return last bgcolor entered
 end

要将背景色应用于表单,只需在模板中的form_for 上方添加div 标签:

<div style="background-color:<%= @last_bgcolor %>"> 
 <%= form_for @user_preference do |u|%>
  .....
  #your form code
 <% end %>
</div>  #close the div after your form_for closed by <% end %>

如果@last_bgcolor 返回nil,那么您将看到默认表单的背景颜色。

如果您希望在选择颜色时用户可以在提交数据之前进行预览,那么我已经实现了示例演示。检查此Working Demo

【讨论】:

  • @cyborg :很高兴知道它对您有帮助。 :)
【解决方案2】:

要获取最后保存的背景,您需要先找到记录。在您的控制器中:

 def new
        @user_preference = UserPreference.new
        # Find the last record 
        @last_preference = UserPrefrence.find(insert_your_params_here)
 end

并更新你的观点:

<div style="<%= 'background-color:#{@last_preference.bgcolor};' %>"</style></div>

之后,您可以决定将this script 添加到您的表单中以提高可用性。

【讨论】:

    猜你喜欢
    • 2017-06-02
    • 1970-01-01
    • 2021-02-27
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    相关资源
    最近更新 更多