link_to对象的触发方法

时间:2012-08-10 23:32:47

标签: ruby-on-rails

我似乎无法回答的快速问题,因为我特别需要它:

我在link_to文件中有html.erb行代码:

<%= link_to "no thanks" %>

我想点击此链接以触发我在此“treating.rb”模型文件中设置的:reject状态方法:

class Treating < ActiveRecord::Base
  attr_accessible :intro, :proposed_date, :proposed_location, :requestee_id, :state

  state_machine :state, :initial => :pending do

    event :reject do
        transition [:pending] => :rejected
    end

    event :reply do
        transition [:pending, :rejected] => :replied
    end

    event :archive do
      transition [:rejected] => :archived
    end
  end
  ...
end

我在link_to代码行中放入什么来获取'待遇'是指将其状态从“待定”更改为“已拒绝”?我已经尝试action =>method =>但没有成功。

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要执行控制器操作,例如:

# ?.html.erb
<%= link_to "no thanks", reject_treating_path(@treating), method: :post %>

# config/routes.rb
resources :treatings do
  member do
    post :reject
  end
end

# app/controllers/treatings.rb
class TreatingsController < ApplicationController
  # POST /treatings/:id/reject
  def reject
    current_user.treatings.find(params[:id]).reject!
    redirect_to treatings_path, notice: "Treating was rejected"
  end
end

我已经为治疗资源添加了一个成员动作,并假设治疗属于一个用户。