Ruby on rails Rails用户对电影的评论

Ruby on rails Rails用户对电影的评论,ruby-on-rails,ruby,comments,associations,Ruby On Rails,Ruby,Comments,Associations,我有三个脚手架 用户、评论和电影 在我的应用程序中,我希望用户对电影发表评论,不同的用户可以在电影页面上发表评论 如何创建关联代码,让用户在电影上添加评论,然后在电影页面上显示所有评论?你能告诉我计算注释的代码吗?显示注释的数量并用整数显示 到目前为止我得到了什么 带有主题和正文的注释表 电影表 用户表 user.rb has_many: comments 电影.rb has_many: comments has_many :users, through: comments comment

我有三个脚手架 用户、评论和
电影

在我的应用程序中,我希望用户
电影
发表评论,不同的用户可以在
电影
页面上发表评论

如何创建关联代码,让用户在电影上添加评论,然后在电影页面上显示所有评论?你能告诉我计算注释的代码吗?显示注释的数量并用整数显示

到目前为止我得到了什么

带有主题和正文的注释表 电影表 用户表

user.rb

has_many: comments
电影.rb

has_many: comments
has_many :users, through: comments
comments.rb

belongs_to :users
belongs_to :movies
谢谢

您可能有:

class User < ActiveRecord::Base
  has_many :comments, :dependent => :destroy
end

class Comment< ActiveRecord::Base
  belongs_to :user
  belongs_to :movie
end

class Movies< ActiveRecord::Base
  has_many :comments, :dependent => :destroy
end
class用户:销毁
结束
类注释:销毁
结束
在您的视图中,您可以执行以下操作:

Number of comments : <%= @movie.comments.length %>
<% @movie.comments.each do |comment| %>
  Pseudo : <%= comment.user.pseudo%>
  Body : <%= comment.body %>
<% end %>
评论数量:
伪:
正文:
如果你从Rails开始,你应该看看这个。它的基础非常棒;)

在users.rb中

has_many :movies, through: :comments
在电影中.rb

has_many :users, through: comments
这被称为具有多个关联。参考资料

要计算:

number_of_comments = Comment.all.size
number_of_comments_on_a_movie = Movie.find(movie_id).comments.size
number_of_comments_by_a_user = User.find(user_id).comments.size

你需要的是告诉他们属于什么。因此,您需要在模型中执行以下操作:

注释模型:

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :movie
end
编辑3:

在评论控制器中,您必须将动作指向电影。在控制器中

class CommentsController < ApplicationController
  before_filter :load_movie

  private
    def load_movie
      @movie = Movie.find(params[:movie_id])
    end
对控制器中的显示、新建等操作执行此操作。在创建操作和更新操作中,需要更新html重定向

format.html { redirect_to (@movie, @comment), notice: 'Comment was successfully created.' }


到目前为止,你得到了什么?是的,但是用户如何创建一个评论,然后使其属于一部电影,但是使用你刚刚编辑的代码,它会使评论属于电影吗?使用电影id,就像我们使用的用户id已经在链接中处理过一样。它为特定的电影创建一个movie.comment(id)。@movie是您正在使用的电影模型的特定实例。在routes.rb中,新的电影注释路径是什么?如何让用户在电影页面上创建注释有很多解决方案!您想使用ajax动态添加注释吗?为了管理用户身份验证,我建议您使用gemdevise。之后,您可以在注释控制器中执行:@Comment=Comment.build(:body=>params[“body”],:user=>current_user)
<%= link_to 'New Comment', new_movie_comment_path(@movie) %>
<%= form_for(@comment) do |f| %>
  <%= f.label :user %>
  <%= f.hidden_field :comment, :user_id, current_user_id %>
<% end %>
resources :movies do
  resources :comments
end
class CommentsController < ApplicationController
  before_filter :load_movie

  private
    def load_movie
      @movie = Movie.find(params[:movie_id])
    end
def index
  @comments = @movie.comments.all
end
format.html { redirect_to (@movie, @comment), notice: 'Comment was successfully created.' }
format.html { redirect_to (@movie, @comment), notice: 'Comment was successfully Updated.' }