ruby - rails 内对于二级资源的 update 操作

查看:87
本文介绍了ruby - rails 内对于二级资源的 update 操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我现在有一个一级资源 @post, 对于二级资源 @comment 的 form_for 该怎么处理呢?

  #update 控制器
  def update
    @comment = Post.find(params[:post_id]).comments.find(params[:id])

    # @comment.update(comment_params)
    # redirect_to post_path(@post)
  end

#edit 表单
<%= form_for @comment do |c|%>
<% end %>

虽然在控制器内定义了 @comment 资源但在视图内却显示为空
但是在错误控制台内调试却可以查找到这条资源?

 Post.find(params[:post_id]).comments.find(params[:id])
=> #<Comment id: 25, user: "12", body: "", post_id: 9, created_at: "2017-07-08 08:43:38", updated_at: "2017-07-08 08:43:38">


这个更新表单(edit.html.erb)应该怎么写呀
先行谢过

解决方案

自己解决了
问题在于对 rails 路由理解出错
edit 控制器对应 edit.html.erb 视图
在 edit.html.erb 表单中我们需要这样制定 form_for。 对应的 update action 让数据提交到 update 控制器上, 从而进入 update 控制逻辑

<%= form_for @comment, url: {action: 'update'} do |c|%>
<%= c.text_field :user%>
<%= c.submit '更新' %>
<% end %>

edit 控制器对应 edit.html.erb, 而 update 没有对应视图, update 只负责模型的操作逻辑

  def edit
    @comment = @comments.find(params[:id])
  end

  def update
    @comment = @comments.find(params[:id])
    @comment.update(comment_params)
    redirect_to post_path(@comment.post)
  end

这篇关于ruby - rails 内对于二级资源的 update 操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆