1

试图在 rails 3 中编写一个基本的“类似博客”的应用程序,我被关联所困。我需要创建方法将 post_id 和 user_id 保存在评论表中(我需要它来检索用户编写的所有评论以显示它)

该应用程序有用户(身份验证 - 设计)、帖子(由用户发布 - 但我不确定这对我来说是否重要)和评论(在帖子上,由用户发布)。

评论表有一个 post_id,一个 body,还有一个 user_id

协会:

has_many :comments (In the Post model)
belongs_to :post (In the Comment model)
belongs_to :user (In the Comment model)
has_many :comments (In the User model)

路线:

resources :posts do
  resources :comments
end

resources :users do
  resources :comments
end

帖子显示视图上显示的评论帖子表单:(posts/show.html.erb)

<% form_for [@post, Comment.new] do |f| %>
  <%= f.label :body %>
  <%= f.text_area :body %>
  <%= f.submit %>
<% end %>

最后,评论控制器中的 create 方法:

A.) 如果我写这个,那么 post_id 就会被写入数据库

def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.create!(params[:comment])
  redirect_to @post
end

B.)如果我写这个,一个 user_id 被写...

def create
  @user = current_user
  @comment = @user.comments.create!(params[:comment])
  redirect_to @post
end

我试过:

@comment = @post.comments.create!(params[:comment].merge(:user => current_user))

但它不起作用..我怎样才能写一个保存 user_id 和 post_id 的方法?我是否还必须在评论表单中进行一些更改(例如 <% form_for [@post, @user, Comment.new] do |f| %> ?)

谢谢!

4

1 回答 1

4

为了设置非常相似的东西,我使用了以下表格:

<%= form_for [:place, @comment] do |f| %>
  #form fields here
<%= end %>

然后在评论控制器中:

def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.build(params[:comment])
  @comment.user = User.find(current_user.id)

  respond_to do |format|
  if @comment.save
    format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') }
  else
    format.html { render :action => "new" }
  end
end

结尾

那应该希望能正确地建立关联!顺便说一句,您的意思是在您的路线中将评论嵌套在 :users 下吗?如果您只想在个人资料页面上显示所有用户的评论,您可以执行以下操作:

<p>
  <b>Comments</b>
  <% if @user.comments.empty? %>
    No comments to display yet...
  <% else %>
    <% @user.comments.each do |comment| %>
      <p>
      <%= link_to "#{comment.post.title}", post_path(comment.post_id) %>, <%= comment.created_at %>
      <%= simple_format comment.content %>
      </p>
    <% end %>
  <% end %>
</p>

希望其中的一些帮助!

于 2010-09-17T08:05:58.270 回答