路由错误:没有路由匹配[PUT]" / goals / 4 / edit"

时间:2014-06-22 15:31:20

标签: ruby-on-rails routes put

我正在尝试创建一个按钮,将模型记录属性从false更改为true。我使用form_tag如下:

=form_tag edit_goal_path(goal), method: :post do
  =hidden_field_tag :purchased, value: true
  =submit_tag "Purchase"

这是haml,但随时可以向ERB发布建议。我收到以下错误:

No route matches [POST] "/goals/4/edit"
Rails.root: /home/ben/rails_projects/hartwig

但是,我已经从资源中获得了以下路线:

PUT     /goals/:id(.:format)    goals#update 

我的控制器如下所示:

  def edit
    @goal = Goal.find(params[:id])
  end

  def update
    @goal = Goal.find(params[:id])
    if @goal.update_attributes(goal_params)
      redirect_to '/goals', notice: "Update successful!"
    else
      render '/'
    end
  end
  def goal_params
    params.require(:goal).permit(:item, :description, :picture, :purchased)
  end

我如何让它工作?或者有更好的方法来解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

你的问题是:

I am trying to create a button to change a model record attribute from false to true

所以为什么你要使用表单?我认为更好的方法是创建一个链接或按钮,它将调用 ajax方法< / strong>或正常方法与邮寄路线并更新您的属性。您可以按照以下步骤实现:

一个。为自定义操作创建路由,您将在其中更新属性:

post 'purchase_update/:id' => "goal#update_purchase", as: update_purchase  #post as you want to send your goal id

湾在控制器中创建自定义方法:

def update_purchase
  @goal = Goal.find(params[:id])
  @goal.update_attribute(:purchased, true)
  respond_to do |format|
    format.html {redirect_to your_path, notice: 'purchase updated'}
    format.js {} #if you want to do something by ajax
  end
end

℃。创建将调用此方法的链接:

=link_to "Purchase", update_purchase_path(@goal), method: post

如果你想通过ajax那么

=link_to "Purchase", update_purchase_path(@goal), method: post, remote: true

答案 1 :(得分:1)

您问题的另一个解决方案是向目标控制器添加新方法:

在goal_controller.rb中

def purchase
@goal.update_attribute(:purchased, true)
end

并添加到顶部(只需添加:购买)

before_action :set_goal, only: [:show, :edit, :update, :destroy, :purchase]
在routes.rb中

更改为

resources :goals do
 member do
  post 'purchase'
 end
end

为您的目标添加新的帖子路线 现在您将拥有一个purchase_goal_path,您可以在视图中使用,如下所示:

link_to 'Purchase', purchase_goal_path(@goal), method: :post