【问题标题】:form_for with f.select and options_for_select works for one attribute but not the second带有 f.select 和 options_for_select 的 form_for 适用于一个属性,但不适用于第二个属性
【发布时间】:2016-01-19 23:50:49
【问题描述】:

这似乎是一个非常基本的问题,但我无法弄清楚我做错了什么。我的rails form_for 带有select 和options_for_select。

:plan 属性会根据所选内容正确创建,但对于 plan 属性,无论您选择创建什么内容以及尝试编辑时,它始终是“第 1 年”。它们基本上是相同的,所以我不明白为什么一个有效而另一个无效。提前感谢您的帮助!

创建表单:

<%= form_for @customer do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :phone %>
<%= f.text_field :phone %>
<%= f.label :year %>
<%= f.select :year, options_for_select([['1st Year', 1], ['2nd Year', 2], ['3rd Year', 3], ['4th Year', 4]]) %>
<%= f.label :plan %>
<%= f.select :plan, options_for_select([['15', 15], ['45', 45], ['75', 75], ['105', 105]]) %>
<%= f.submit%>
<%end%>

编辑表格:

<%= form_for @customer do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :phone %>
<%= f.text_field :phone %>
<%= f.label :year %>
<%= f.select :year, options_for_select([['1st Year', 1], ['2nd Year', 2], ['3rd Year', 3], ['4th Year', 4]]) %>
<% if current_user.role == "admin"%>
<%= f.label :plan %>
<%= f.text_field :plan %>
<%else%>
<p>Plan selected: <%=@customer.plan%></p>
<%end%>

<%= f.submit%>
<%end%>

客户控制器:

def create
    @customer = current_user.customers.create(customer_params)
    if current_user.role == "admin"
      redirect_to customers_path
    elsif current_user.role == "customer"
      redirect_to user_customer_path(current_user, @customer)
    else
      redirect_to '/'
    end
  end

  def update
    @customer.update(customer_params)
    if current_user.role === "customer"
      redirect_to customer_path(@customer)
    else
      redirect_to customers_path
    end
  end

private
  def customer_params
    params.require(:customer).permit(:name,:year,:email,:plan,:verification)
  end

【问题讨论】:

    标签: ruby-on-rails ruby forms


    【解决方案1】:

    所以我检查了我的 rails 控制台,发现它确实在工作!这意味着问题在于选择的内容。我在 cmets 中找到了解决方案:select doesn't show selected value

    并且能够使用以下代码使其显示正确的选定值:

    <%= f.select :year, options_for_select([['1st Year', 1.to_i], ['2nd Year', 2.to_i], ['3rd Year', 3], ['4th Year', 4]], selected: @customer.year) %>
    

    【讨论】:

      猜你喜欢
      • 2017-09-04
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 2016-12-09
      • 2010-10-25
      • 2021-06-07
      • 1970-01-01
      • 2013-01-09
      相关资源
      最近更新 更多