【发布时间】:2011-07-16 11:19:03
【问题描述】:
我被这个场景卡住了。让我解释如下。我有一个电影模型,用户可以给电影评分,他可以评论电影。所以我有积分表。根据 cmets 的数量、评分和平均评分等,我在我的电影控制器中编写了一个方法 def points end。
我有一个单独的评论控制器和方法,用于创建 cmets,并且为了给电影评分,我在我的电影控制器中编写了一个用于创建评分的方法。希望我清楚到现在。
所以我的问题陈述是。我想在创建评级和 cmets 时在电影控制器中调用此积分方法。
为了简要了解我在这里粘贴我的代码。
在电影控制器中我的两种方法(评分和分数)
def rate
@movie= Movie.find(params[:movie_id])
@count=0
@test= Rating.find(:last, :conditions=>['movie_id=?', @movie.id])
unless @test.nil? || @test.blank?
@count= @test.count
end
if(params[:submitted])
if @movie.ratings.create(:movie_id => params[:movie_id], :rate => params[:rating], :user_id=> current_user.id, :count=> @count+1)
points
flash[:success] = "Rating was successfully saved."
else
flash[:error] = 'Error. Rating was not saved. Try again later.'
end
redirect_to @movie
end
end
def points
@user= current_user
@movie= Movie.find(params[:movie_id])
total_comments_by_user=Comment.find(:all, :conditions=>['user_id=? AND movie_id=?',@user.id,@movie.id]).count
user_who_rated= Rating.find(:all, :conditions=>['user_id=? AND movie_id=?',@user.id,@movie.id])
@user_who_rated.each do |ur|
if @user=ur.user_id
@ratings_of_each_user=ur.rate
end
end
@over_all_comments_of_movie=Comment.find(:all, :conditions=> ['movie_id=?', @movie.id]).count
@records=Rating.find(:all, :conditions => ['movie_id=?',@movie.id]).collect(& :rate)
unless @records.nil? || @records.blank?
@average_rating = 0.0
@records.each do |r|
@average_rating += r
end
@average_rating = @average_rating/@records.size
end
unless @ratings_of_each_user.nil? || @ratings_of_each_user.blank?
if @total_comments_by_user.nil? || @total_comments_by_user.blank?
else
@div_one=@ratings_of_each_user*@total_comments_by_user
@div_two=@over_all_comments_of_movie* @average_rating
@total=0.0
@total=@div_one.to_f/@div_two.to_f
@find_user_in_points= Point.find(:all, :conditions=> ['user_id=? AND movie_id=?',current_user.id,@movie.id])
if @find_user_in_points.nil? || @find_user_in_points.blank?
Point.create(:user_id=> current_user.id, :movie_id=>@movie.id, :points=> @total)
else
@find_user_in_points.each do |f|
if f.user_id= current_user.id
f. update_attributes(:points=> @total)
end
end
end
end
end
end
现在 cmets 控制器
def create
@user=current_user
@movie = Movie.find(params[:movie_id])
@select_params= params[:choice_list] || []
if @select_params.nil? || @select_params.blank?
@comment = @movie.comments.create(params[:comment])
@comment.update_attributes(:user_id=>@user.id, :commenter => @user.username)
else
@comment= @movie.comments.create( :commenter => "user", :body=>params[:comment][:body] , :movie_id=> @movie.id, :user_id=>@user )
end
redirect_to movie_path(@movie)
end
def destroy
@comment = Comment.find(:all, :conditions=>['id=?',params[:id]])
@comment.delete
redirect_to movie_path(@movie)
end
我在我的视图文件中有评价电影链接和一个表格来为电影添加评论。我只想在创建评分和创建 cmets 时调用该 points 方法,以便我可以在内部执行我的积分计算并更新我的积分表。
请指导我。是否可以从另一个控制器调用一个控制器中的方法,如果可以的话,告诉我如何在同一个控制器中调用方法。
【问题讨论】:
-
为什么不创建一个可以从两个控制器调用的共享方法?你真的不应该从控制器 B 调用控制器 A...控制器方法仅用于浏览器请求。
标签: ruby-on-rails