[英]Passing a collection_selection and text_field values in a form_for, rails
The Attraction model belongs to Destination. 吸引力模型属于目的地。
I'm trying to create a new attraction (text_field :name) but also linking it to an already-created destination. 我正在尝试创建一个新的吸引力(text_field:name),但也将其链接到一个已经创建的目的地。 These destinations are rendered in a drop-down menu with this collection_select tag.
这些目的地在带有该collection_select标记的下拉菜单中呈现。 By clicking submit, I'm want the attraction to be created and saved in the activerecord database with the Destinations foreign key.
通过单击提交,我希望使用“目标”外键将景点创建并保存在activerecord数据库中。
f.collection_select(:attraction, :destination_id, Destination.all, :id, :name) %> f.collection_select(:attraction,:destination_id,Destination.all,:id,:name)%>
The whole block looks like this at the moment: 目前,整个块如下所示:
<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>
How can I save the attraction to the database with the appropriate destinaton? 如何使用适当的目的地将景点保存到数据库中? Thanks in advance!!
提前致谢!!
I haven't use f.collection_select()
so not sure what it is called inside the params, but lets assume for the following code that it's params[:attraction][:destination_id]
. 我没有使用
f.collection_select()
所以不确定在params内部调用什么,但是对于以下代码,假设它是params[:attraction][:destination_id]
。 You can change your create action to: 您可以将创建操作更改为:
def create
@destination = Destination.find(params[:attraction][:destination_id])
@attraction = @destination.attractions.build(params[:attraction])
if @attraction.save
...
else
...
end
end
That's assuming that you've created a has_many
and belongs_to
association. 假设您已经创建了
has_many
和belongs_to
关联。
If you run into a mass-assignment error then change the first line 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.