Rails路由错误,因为控制器def

时间:2013-07-19 12:48:17

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

我是Rails的初学者,并在Controller中创建了一个def set_star,以便在onclick上更改属性。

class EbmsController < ApplicationController
  def index
    @ebms = Ebm.all
  end

  def destroy
    @ebm = Ebm.find(params[:id])
    @ebm.destroy
    redirect_to categories_path
  end

  def create
    @ebm = Ebm.new(params[:ebm])
    @ebm.save
    redirect_to categories_path
  end

  def set_star
    @ebm = Ebm.find(params[:id])
    @ebm.write_attribute(:star, '1')
    redirect_to categories_path
  end
end

按钮如下所示:

<% for ebm in @ebms do %>
  <tr>
    <td><%= ebm.number %></td>    
    <td><%= ebm.text %></td>
    <td><%= ebm.content %></td>
    <td><%= ebm.star %></td>
    <td><%= link_to 'Star', ebm, :method => :set_star, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>

但不知怎的,它不会工作,当我点击按钮时,我总是收到路由错误:

 No route matches [POST] "/ebms/1"

在我的路线中,我只是定义了:

 resources :ebms

所以,我不知道我做错了什么!感谢。

1 个答案:

答案 0 :(得分:5)

routes.rb添加行

put 'ebms/:id/star', to: 'ebms#set_star', as: 'set_star'

然后按如下所示更改link_to

<%= link_to 'Star', set_star_path(ebm), method: :put, confirm: 'Are you sure?' %>

正如Mattherick指出的那样,也将你的控制器改为@ebm.update_attribute(:star, '1')