0

我有一个带有Movies的简单模型和一个用于Users的模型。保存用户看过的电影的最佳方法是什么?我应该创建一个“seen_movie”模型吗?和它的控制器?应该如何调用切换状态的操作?我想过这样的事情:

模型:

class SeenMovie < ActiveRecord::Base
    belongs_to :user
    belongs_to :movie

    def self.has_seen?(user)
        @has_seen = SeenMovie.find_by_user(user)
        return @has_seen
    end
end

控制器:

 class SeenMoviesController < ApplicationController
    before_filter :require_login

    def update # any other name? how to call this action?
        if has_seen?(current_user)
            render text: "delete record"
        else
            render text: "create record"
        end
    end

    private

    def seen_movie_params
        params.require(:rating).permit(:movie_id)
    end
end

我不确定这是否有效,以及它是否是一个好方法。对我来说,它看起来不是切换简单状态的好方法......

信息:我是 Rails 的新手(来自 PHP)

4

1 回答 1

3

这是我将如何处理它:

在您的模型中:

class User < AR::Base
  has_many :seen_movies
  has_many :movies, through: :seen_movies

  def has_seen?(movie)
    movies.where(id: movie.id).first.present?
  end
end

class Movie < AR::Base
  has_many :seen_movies
  has_many :users, through: :seen_movies
end

在您的控制器中:

class SeenMoviesController < ApplicationController
    before_filter :require_login

    def update
      @movie = Movie.find(params[:movie_id])
      if current_user.has_seen?(@movie)
        render text: "delete record"
      else
        render text: "create record"
      end
    end

    private

    def seen_movie_params
      params.require(:rating).permit(:movie_id)
    end
end

在您看来:

<% @movies.each do |movie| %>
  <%= link_to "Seen it!", seen_movie_path(movie_id: movie.id), method: :put %>
<% end %>
于 2013-10-01T18:59:16.677 回答