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. These destinations are rendered in a drop-down menu with this collection_select tag. By clicking submit, I'm want the attraction to be created and saved in the activerecord database with the Destinations foreign key.
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]
. 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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.