Rails 4简单表单collection_select

29

如何将以下内容简化翻译?

<%= form_for(@bill) do |f| %>

<%= f.label :location_id %>
<%= f.collection_select(:location_id, @locations, :id, :location_name, 
      {:selected => @bill.location_id}) %>

我无法使用简单的关联,因为@locations是where查询的结果。

4个回答

63

试一试

<%= simple_form_for @bill do |f| %>
   <%= f.input :location,:collection => @locations,:label_method => :location_name,:value_method => :id,:label => "Location" ,:include_blank => false %>
   <%= f.button :submit %>
<%end%>

希望这可以帮助到您


删除额外的“collection:”后,代码可以正常工作,但会添加一个空格,这不是我想要的。 - markhorrocks
@markhorrocks 有一个名为 include_blank => false 的选项,只需添加它即可。 - Viren
@markhorrocks编辑了答案,并加入了 include_blank => false选项。 - Viren

7
这里是最终版:
<%= f.input :location_id, collection: @locations, label_method: :location_name, value_method: :id,label: "Location", include_blank: false, selected: @bill.location_id %>

2

简单来说,如果我们有位置和账单之间的关联,我们可以这样做:

<%= simple_form_for @bill do |f| %>
  <%= f.association :location, collection: @locations, priority: @bill.location %>
  <%= f.button :submit %>
<% end %>

希望这能有所帮助。


有这样一个关联,但是@locations = Location.where(club_id: club_id),不过看起来它仍然可以工作? - markhorrocks
如果您没有适当的关联,则为: <%= f.input :location, collection: @locations %> - Rails Guy
关联在两个模型中都有定义,但对于位置(Location)却产生了某种哈希值而没有错误。Rails表单助手运行良好。 - markhorrocks
谢谢!这正是我一直在寻找的。一种可以拥有自定义集合但仍然以正确格式发送关联嵌套字段的方法。 - Augusto Samamé Barrientos

-1
在您的位置模型中,您还可以创建以下内容:
def to_label
  location_name
end

to_label 是视图/显示的职责,不应该在模型中定义(模型只应包含业务逻辑和数据库相关内容)。 - Celso Dantas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接