ruby-on-rails - 如何在 Rails 中获取帖子 ID?

标签 ruby-on-rails ruby-on-rails-3

这就是我为一个简单的博客定义模型的方式

def User
  has_many :comments, :dependent => :destroy
  has_many :posts
end

def Post
  belongs_to :user
  has_many :comments
end

def Comment
  belongs_to :user
  belongs_to :post
end

在我的 Post Controller 中我有这段代码,这样我就可以在 View 中创建评论

  def show
    @post = Post.find(params[:id])
    @comment = Comment.new
    respond_to do |format|
        format.html # show.html.erb
        format.xml  { render :xml => @post }
    end
  end

然后在我的 Comment#create 中有这个

  def create
    @comment = current_user.comments.create(params[:comment])
    if @comment.save
      redirect_to home_show_path
    else
      render 'new'
    end
  end

我应该怎么做才能让我的评论模型可以接收到 post_id?我已在我的 Post show View 中完成此操作作为修复,但还有其他更好的方法吗?

<%= f.hidden_field :post_id, :value => @post.id %>

最佳答案

通过表单中的隐藏字段设置 post_id 不一定有错 - 但它确实意味着人们可能会将他们的评论与任何随机帖子相关联。

更好的方法可能是对帖子的评论使用嵌套资源。为此,请在您的 routes.rb 文件中设置以下内容:

resources :posts, :shallow => true do 
  resources :comments
end

那么你的表单应该是这样的:

<%= form_for @comment, :url => post_comments_path(@post) do %>
   ...
<% end %>

这意味着表单 POST 到路径 /post/[:post_id]/comments - 这反过来意味着 post_id 可以作为参数提供给 Controller :

def create
   @comment = current_user.comments.new(params[:comment])
   @comment.post = Post.find(params[:post_id])
   if @comment.save
      ...
   end
end

这样做的好处是可以使用帖子 ID 对帖子进行选择,如果找不到帖子,则会引发错误。

也可能值得稍微重写该 Controller 方法,以便 Post.find 排在第一位:

def create
   @post = Post.find(params[:post_id])
   @comment = @post.comments.new(params[:comment])
   @comment.user = current_user
   if @comment.save
      ...
   end
end

希望对您有所帮助。

关于ruby-on-rails - 如何在 Rails 中获取帖子 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6480713/

相关文章:

ruby-on-rails - 如何使用 will_paginate 设置搜索?

ruby-on-rails - Ruby on Rails : How can i get the username from users table with Post. 分页?

ruby-on-rails-3 - Rails 插入数组保存对象

ruby-on-rails - 强参数 : Hash param is missing or the value is empty

css - 从 rails 3.2 升级到 4.1,没有加载 scss 或 css

ruby-on-rails - Haml 更新后 Capybara::Poltergeist::MouseEventFailed (4.0.7 => 5.0.2) [RAILS]

ruby-on-rails - Rails 3.2 重定向/images/* 到/assets/*

javascript - UJS + Bootstrap按钮加载

ruby-on-rails - 使用 Capistrano 部署,未读取 JAVA_HOME

ruby-on-rails - Rails 3.1,jQuery : Append data to a form before sending it out