[英]Is this a correct way of saving associations in rails?
I'm trying to save to two association tables (tours/stops, and stops/venues) while saving one model (stops). 我试图在保存一个模型(停靠点)的同时保存到两个关联表(游览/停靠点,以及停靠点/地点)。 Tours has_many stops and stops belongs to both the association tables.. but because I'm in the Stops controller I can only seem to save via @tour.stops.create so I manually did a create..
Tours has_many停靠点和停靠点都属于两个关联表..但是由于我在Stops控制器中,所以似乎只能通过@ tour.stops.create保存,所以我手动进行了创建。
Here's my code from the stops controller 这是我的Stops Controller的代码
class StopsController < ApplicationController
def create
tour_id = params[:stop][:tour_id]
#check to make sure venue matches before saving
venue_name = params[:stop][:venue_name]
venue_id = Venue.find_by(name: venue_name).id
@tour = Tour.find(tour_id)
@stop = @tour.stops.create(strong_params)
#this seems like it might be ghetto
Stopsvenuesmembership.create!(venue_id: venue_id, stop_id: @stop.id)
I believe the traditional way of doing this would be 我相信这样做的传统方式是
@stop = @tour.stops.create(params)
@venue = Venue.find_by_name(venue_name) # or however you want to find it
@venue.stops << @stop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.