繁体   English   中英

在form_for,rails中传递collection_selection和text_field值

[英]Passing a collection_selection and text_field values in a form_for, rails

吸引力模型属于目的地。

我正在尝试创建一个新的吸引力(text_field:name),但也将其链接到一个已经创建的目的地。 这些目的地在带有该collection_select标记的下拉菜单中呈现。 通过单击提交,我希望使用“目标”外键将景点创建并保存在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>

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

我没有使用f.collection_select()所以不确定在params内部调用什么,但是对于以下代码,假设它是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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM