这是保存rails中关联的正确方法吗?

时间:2014-01-10 03:36:31

标签: ruby-on-rails activerecord ruby-on-rails-4 associations

我正在尝试保存两个关联表(巡视/停止和停止/场地),同时保存一个模型(停止)。 Tours has_many停止和停止属于两个关联表..但因为我在Stops控制器中我似乎只能通过@ tour.stops.create保存,所以我手动创建了一个..

这是来自停止控制器的代码

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)

1 个答案:

答案 0 :(得分:0)

我相信传统的做法是

@stop = @tour.stops.create(params)

@venue = Venue.find_by_name(venue_name) # or however you want to find it
@venue.stops << @stop