1

我有三个脚手架 用户评论Movies

在我的应用程序中,我希望用户评论Movies并且不同的用户可以在页面上评论。Movie

我将如何创建允许用户在电影上添加评论然后在电影页面上显示所有评论的关联代码?能否请你告诉我计算评论的代码,所以显示有多少评论并以整数显示

到目前为止我所拥有的

带有主题和正文电影表的评论表用户表

用户.rb

has_many: comments

电影.rb

has_many: comments

评论.rb

belongs_to :users
belongs_to :movies

谢谢 !

4

3 回答 3

2

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

评论型号:

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

用户模型:

class User < ActiveRecord::Base
  has_many :comments
end

电影型号:

class Movie < ActiveRecord::Base
  has_many :comments
end

您需要生成迁移以将外键列添加到注释表中。一旦你有了它,你需要做的就是通过他们的 id 将评论附加到电影和用户。然后让他们在视图中显示评论:

<% @movie.comments.each do |comment| %>
  <%= comment.text %>
<% end %>

编辑:要创建评论,您需要一个链接来添加新评论。在视图中:

<%= 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 %>

最后一部分假设您有一个活动会话。

编辑2:

在路由中,您可以将评论资源嵌套在电影资源中:

resources :movies do
  resources :comments
end

编辑 3:

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

class CommentsController < ApplicationController
  before_filter :load_movie

  private
    def load_movie
      @movie = Movie.find(params[:movie_id])
    end

私有部分需要位于控制器的底部。完成后,更新操作以使用@movie。

def index
  @comments = @movie.comments.all
end

为控制器中的显示、新建等操作执行此操作。在创建操作和更新操作中,您需要更新 html 重定向。

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

format.html { redirect_to (@movie, @comment), notice: 'Comment was successfully Updated.' }
于 2013-06-06T15:23:36.443 回答
0

你可能有 :

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

在您的观点中,您可以执行以下操作:

Number of comments : <%= @movie.comments.length %>
<% @movie.comments.each do |comment| %>
  Pseudo : <%= comment.user.pseudo%>
  Body : <%= comment.body %>
<% end %>

如果您从 Rails 开始,您应该看看这个教程。这对于基础知识来说太棒了;)

于 2013-06-06T15:23:23.350 回答
0

在 users.rb 中

has_many :movies, through: :comments

在电影.rb

has_many :users, through: comments

这称为has-many-through关联。参考这里

计算:

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
于 2013-06-06T15:23:35.727 回答