【问题标题】:Passing a collection_selection and text_field values in a form_for, rails在 form_for、rails 中传递 collection_selection 和 text_field 值
【发布时间】:2013-04-16 21:34:01
【问题描述】:

Attraction 模型属于 Destination。

我正在尝试创建一个新景点 (text_field :name),但同时也将其链接到一个已经创建的目的地。这些目的地在带有此 collection_select 标记的下拉菜单中呈现。通过单击提交,我希望使用 Destinations 外键创建吸引力并将其保存在 activerecord 数据库中。

f.collection_select(:attraction, :destination_id, Destination.all, :id, :name) %>

现在整个区块是这样的:

<h1>New attraction</h1>

选择城市

<%= f.collection_select(:attraction, :destination_id, Destination.all, :id, :name) %>   

<div class ="field">
  <%= f.label :name %>
  <%= f.text_field :name %>
</div>

<div class="actions">
  <%= f.submit %>
</div>

如何将景点保存到具有适当目的地的数据库中?提前致谢!!

【问题讨论】:

    标签: ruby-on-rails forms collections form-for


    【解决方案1】:

    我没有使用f.collection_select(),所以不确定它在参数中被称为什么,但我们假设下面的代码是params[:attraction][:destination_id]。您可以将创建操作更改为:

    def create
      @destination = Destination.find(params[:attraction][:destination_id])
      @attraction = @destination.attractions.build(params[:attraction])
      if @attraction.save
        ...
      else
        ...
      end
    end
    

    假设您已经创建了 has_manybelongs_to 关联。

    如果遇到批量分配错误,请将第一行更改为:

    @destination = Destination.find(params[:attraction].delete(:destination_id))
    # this will return the deleted value, and in the next line of code
    # you'll have the rest of the params still available
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多