我有一个简单的模型电影和用户的模型。什么是保存用户看过哪部电影的最佳方式?我应该创建一个“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)
答案 0 :(得分: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 %>