【问题标题】:Rails 3.1 Post/Comment model for blog -- How to submit comments via ajax?Rails 3.1 博客的帖子/评论模型——如何通过 ajax 提交评论?
【发布时间】:2011-10-31 01:03:01
【问题描述】:

我正在尝试了解如何使用远程表单并使用 Post 模型 has_many Comments 的应用程序示例。

假设我使用通用 rails 脚手架来创建/设置帖子/评论模型、控制器、默认视图、路由等,我的 app/views/posts/show.html 应该是什么样子?

具体我很困惑:

  1. 评论表单应该发到哪里?
  2. 应该包含哪些参数?
  3. 我是否需要使用隐藏属性,例如f.hidden_field :post_id, :value => @post.id

谢谢!

【问题讨论】:

  • 查看 railscasts.com,我确信那里有一些有用的截屏视频...

标签: ruby-on-rails ruby ruby-on-rails-3 forms ujs


【解决方案1】:

假设您的帖子 has_many cmets...

routes.rb(嵌套资源)

resources :posts do
  resources :comments
end

在您的 cmets_controller 中

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

形式:

=form_for [@post, @comment], :remote => true do |f|
  =f.text_field :text
  =f.submit

【讨论】:

  • 非常感谢杰西。将 form_for 与嵌套路由一起发布有助于澄清我哪里出错了。
猜你喜欢
  • 2011-07-24
  • 1970-01-01
  • 2017-07-29
  • 2016-09-09
  • 1970-01-01
  • 2023-04-10
  • 2021-04-16
  • 1970-01-01
  • 2019-02-20
相关资源
最近更新 更多