ruby-on-rails - Rails 关联(belongs_to、has_many)无法使用创建方法(用户、帖子、评论)在表中保存 2 个 ID

标签 ruby-on-rails ruby associations has-many belongs-to

尝试在 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 view上显示的评论post表单:(posts/show.html.erb)

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

最后,评论 Controller 中的创建方法:

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| %> ?)

谢谢!

最佳答案

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

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

然后在评论 Controller 中:

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

结束

希望这应该能正确地建立关联!顺便说一句,您的意思是要将评论嵌套在您的 route 的 :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>

希望对您有所帮助!

关于ruby-on-rails - Rails 关联(belongs_to、has_many)无法使用创建方法(用户、帖子、评论)在表中保存 2 个 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3732198/

相关文章:

ruby-on-rails - has_many 上的自定义范围,:through association (Rails 4)

javascript - 将数据从 Rails Controller 传递到 React 组件

ruby-on-rails - 在 has_many 关系中提取子对象的 id

ruby-on-rails - Ruby 有很多关联错误

java - 如何在jpa/hibernate中实现这个简单的关联

ruby-on-rails - 对 Rails 中的对象进行排序

sql - 使用 Rails 和 SQL 在数据库中保存多条温度曲线(同时测量)的最佳方法是什么

javascript - Ruby On Rails 3.1 - Assets 管道 - Assets 渲染两次

ruby - 在 CentOS 64 位上的 Ruby 1.9.2 中安装 ruby​​gem 'mysql2' 时出现编译器错误

mysql - 搜索引擎过滤器::每个过滤器的预计数结果