如何通过另一个模型关联模型?

时间:2016-01-08 11:28:34

标签: ruby-on-rails angularjs

对于我的rails4 / angular app,我有一个电影模型和一个预告片模型。当我创建电影记录时,我还创建了一个或多个预告片记录。我想创建一个json响应,其中电影预告片包含在每部电影中。

所以我需要在两个模型之间建立某种关联。

预告片只属于一部电影,但电影可以有很多预告片。所以在我的拖车模型中,

belongs_to :movie

在我的电影模型中,

has_many :trailers

我的预告片控制器中的创建功能

def create
  trailer = Trailer.create(trailer_params)
  redirect_to :root 
end

我的电影控制器中的创建功能,

def create

   @movie = Movie.find_or_create_by movie_params
   current_user.movies << @movie
   redirect_to :root
   current_user.followers.each { |follower| @movie.create_activity(key: 'movie.create', owner: current_user, recipient: follower) }
end

在我的电影控制器中,我有这个索引,

def index
  @movie = Movie.all
  respond_to do |format|
    format.json do
      render :json => @movie.to_json(include: :trailers)
    end
  end
end

json渲染的输出是这样的,

{  
  "id":7,
  "title":"The Revenant",
  "release_date":"2016-01-28",
  "image":"/oXUWEc5i3wYyFnL1Ycu8ppxxPvs.jpg",
  "movie_id":"281957",
  "backdrop":"/kiWvoV78Cc3fUwkOHKzyBgVdrDD.jpg",
  "trailers":[  

  ]
}

有没有办法可以将预告片与电影联系起来,以便将它们包含在电影中?

*已更新*

我在模板中有一个带有ng-click的按钮,

.addmovie{"ng-click" => "addMovie(movie)"}

在我的角度控制器中调用addMovie函数,

在这个函数中,我运行了几个角度服务来获取我的数据,但这是创建预告片的函数,

movieAdd.trailer(movie.id)
.then(function(response){
  $scope.youtubeTrailer = [];

  angular.forEach(response.results, function(item){
    $scope.youtubeTrailer = [];
    $scope.youtubeTrailer.push(item.key);
    var youtubeLink = $scope.youtubeTrailer.toString();
    createTrailer.create({
      link:     youtubeLink,
      movie_id: $scope.movieListID.id
    }).then(init);

  })

0 个答案:

没有答案