通过AJAX更改对象的状态

时间:2014-01-11 22:16:44

标签: ruby-on-rails ajax state-machine

我遇到了使用state_machine的问题。我无法通过AJAX找到如何在show page中更改对象(trip)的状态。我是铁轨和网络开发的新手,所以如果可以写一个简单的例子,那将是最好的解释。

trip.rb

class Trip < ActiveRecord::Base
 attr_accessible :content, :title

 state_machine :state, initial: :draft do

  state :draft
  state :published

  event :publish do
    transition :draft => :published
  end

  event :hide do
    transition :published => :draft
  end
 end
end

show.html.erb

<%= button_to 'publish', action: :publish %>
<%= button_to 'hide', action: :hide%>

<h3><%= @trip.title %></h3>
<p><%= @trip.content%></p> 

1 个答案:

答案 0 :(得分:0)

感谢您提出的问题&amp;会给你一个答案。毕竟,每个人都必须从某个地方开始!


<强>路线

#config/routes.rb
resources :trip do 
    post :publish
    post :hide
end

生成网址:domain.com/trips/:id/publish&amp; domain.com/trips/:id/hide


<强>控制器

#app/controllers/trips_controller.rb
def publish
    task = Task.find(params[:id])
    task.publish!

    respond_to do |format|
        format.js
    end
end

def hide
    task = Task.find(params[:id])
    task.hide!

    respond_to do |format|
        format.js
    end
end

查看

<%= button_to 'publish', action: :publish, remote: :true, method: :post %>
<%= button_to 'hide', action: :hide,  remote: :true, method: :post %>

<h3><%= @trip.title %></h3>
<p><%= @trip.content%></p>

<强> JS

#app/views/trips/publish.js.erb
// your JS here