Rails 4表单:在选择字段

时间:2015-10-23 17:58:55

标签: ruby-on-rails forms ruby-on-rails-4 drop-down-menu

Stack Overflow上有类似的问题,例如this onethat one,我尝试了建议的答案,但我无法解决问题。

我有一个Rails表单 - 一个simple_form表单 - 在我的新视图中包含以下字段:

<div class="field">
  <%= f.label :price, "Hourly Rate ($)" %><%= f.select :price, ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100'] %>
</div>

然后,我想在编辑视图中重新显示此表单,并将值保存到数据库中,所以我尝试了:

<div class="field">
  <%= f.label :price, "Hourly Rate ($)" %><%= f.select :price, ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100'], :selected => current_user.price %>
</div>

问题是select字段显示的是第一个值而不是我期望的值。

- - - -

更新:根据下面给出的答案,我实施了以下代码:

<div class="field">
  <%= f.label :price, "Hourly Rate ($)" %>
  <%= f.select :price, [['10', '10'],['20','20'],['30','30'],['40','40'],['50','50'],['60','60'],['70','70'],['80','80'],['90','90'],['100','100']], selected: current_user.price, include_blank: 'Select your price' %>
</div>

它似乎不起作用。除非我弄错了?

- - - -

知道如何使这项工作吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

<div class="field">
  <%= f.label :price, "Hourly Rate ($)" %><%= f.select :price, [['10', '10'],['20','20'],['30','30'],['40','40'],['50','50'],['60','60'],['70','70'],['80','80'],['90','90'],['100','100']], selected: current_user.price, include_blank: 'Select your price' %>
</div>

你应该传递一个数组数组,其中左边的单元格是名称,右边的​​数字是值,然后通过值而不是按名称传入,你也应该以第一种形式使用它:

<div class="field">
  <%= f.label :price, "Hourly Rate ($)" %><%= f.select :price, [['10', '10'],['20','20'],['30','30'],['40','40'],['50','50'],['60','60'],['70','70'],['80','80'],['90','90'],['100','100']] %>
</div>

答案 1 :(得分:1)

您不需要两个单独的表格。

new.html.erb edit.html.erb 中的

表示以下内容:

public class Recipe {
    [Key]
    public int RecipeId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual ICollection<RecipeIngredient> Ingredients { get; set; }  
}

public class Ingredient {
    [Key]
    public int IngredientId { get; set; }
    [Required]
    public string Name { get; set; }
    public bool Organic { get; set; }
    public bool Vegan { get; set; }
    public virtual ICollection<RecipeIngredient> Recipes { get; set; } 
}

public class RecipeIngredient {
    [Key, Column(Order = 0)]
    public int RecipeID { get; set; }
    [Key, Column(Order = 1)]
    public int IngredientID { get; set; }
    public double Quantity { get; set; }
}

然后在 _hourly_rate.html.erb 中输入以下内容:

<%= render 'hourly_rate' %>

其中<div class="field"> <%= f.label :price, "Hourly Rate ($)" %> <%= f.select :price, options_for_select([['10',1], ['20',2], ['30',3], ['40',4], ['50',5], ['60',6], ['70',7], ['80',8], ['90',9], ['100',10]], @your_obj.price) %> </div> 类似于1,2,3 ...(或者如果您愿意,可以将其修改为实际价格。您只需要相应地更改数组。)

@your_obj.price方法是一个帮助器,其第二个参数允许您通过传递其值来预先选择一个选项。有关更多信息,请查看docs