我的 Rails 3 应用程序中有 3 个模型:
用户
模型:
has_many :videos, :dependent => :destroy
控制器:
before_filter :signed_in_user
def show
@user = User.find(params[:id])
end
def signed_in_user
unless signed_in?
store_location
redirect_to signin_path, notice: "Please sign in."
end
end
视频
模型:
belongs_to :user
has_many :surveys, :dependent => :destroy
控制器:
before_filter :signed_in_user
def signed_in_user
unless signed_in?
store_location
redirect_to signin_path, notice: "Please sign in."
end
end
def show
@video = Video.find(params[:id])
@original_video = @video.panda_video
@h264_encoding = @original_video.encodings["h264"]
@surveys = Survey.all
@user = User.find(params[:id])
end
民意调查
模型:
belongs_to :video
控制器:
before_filter :signed_in_user
def signed_in_user
unless signed_in?
store_location
redirect_to signin_path, notice: "Please sign in."
end
end
def show
@survey = Survey.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @survey }
end
end
所以在我的应用中,一个用户有很多视频,每个视频都有很多调查(又名评论)。想想烂番茄是如何运作的。用户已登录以访问视频或撰写评论。用户在登录时提交的任何评论都会自动与该用户相关联……这就是我试图通过我的应用程序来解决的问题。
如何将用户 ID 与评论相关联?现在,当用户登录时,他的名字会自动与所有评论相关联,无论他是否写过评论。