2012-02-01 56 views
0

我希望用戶單擊按鈕在我的發佈頁面中發佈事件。從空的form_for更新屬性

的意見/事件/ publish.html.erb

<%= form_for @event do |p| %>  
    <%= p.submit "Yes publish my event now" %> | 
    <%= link_to "Cancel", events_path %> 
<% end %> 

用戶可以從我的索引頁面獲取到發佈頁面

的意見/事件/ index.html.erb

<% for event in @events %> 
    <%= link_to "Publish", publish_path(:id => event) %> 
<% end %> 

Publish_path已被路由定義爲在事件控制器中

的routes.rb

match 'publish' => 'events#publish', :as => :publish 

這裏是我的事件控制器

events_controller.rb

def publish 
    @event = Event.find(params[:id]) 
end 

當我添加的代碼(見下文),以更新事件模型在我的發佈操作中,控制器將更新屬性,但是當用戶單擊我的ind中的「發佈」鏈接時恩。

通過此代碼,用戶在點擊索引中的發佈鏈接時看不到我的發佈頁面。相反,它們將被髮送回索引頁面,但所有屬性都會更新。

def publish 
    @event = Event.find(params[:id]) 
    if @event.update_attributes(:published_at => DateTime.now, :publish => true) 
    flash[:success] = "Your event has been publish" 
    redirect_to events_path 
    end 
end 

的問題是,如何我從索引頁的用戶 - >發佈頁面 - >點擊提交 - >更新屬性 - >使用閃光燈消息返回到索引頁?

+0

+1瞭解詳情,但是您能否再解釋一下問題?發生了什麼,你不想發生? – 2012-02-01 15:48:21

+0

索引頁是什麼意思?你的'EventsController'的'index'動作?你在該頁面上顯示Flash嗎? – Mischa 2012-02-01 16:03:58

+0

目前發生的事情是索引頁面 - >點擊鏈接轉到發佈頁面 - >更新屬性 - >索引頁面。 – Moose 2012-02-01 22:31:09

回答

1

嗯,我猜你正在努力實現以下工作流程,Index page -> Publish page -> click submit -> update the attributes -> return back to Index page with flash message

都使用單一的行動,我們無法實現的,因此增加一個動作

events_controller

# Will take user to confirm page, where we display the form with "Yes publish now" and "cancel" button 
def confirm_publish 
    @event = Event.find(params[:id]) 
end 

# When user clicks the "yes publish now" button, request should come here and perform the same. 
def publish 
    @event = Event.find(params[:id]) 
    if @event.update_attributes(:published_at => DateTime.now, :publish => true) 
    flash[:success] = "Your event has been publish" 
    redirect_to events_path 
    end 
end 

相應地,我們需要修改視圖和路線。

+0

在我的** confirm_publish.html.erb **中,我添加了<%= form_for @event,url => {:action =>'publish'},do | p | %>'。但後來它說'沒有路線匹配{:action =>「發佈」,:控制器=>「事件」}'我已經在我的** routes.rb **中有'resources:events'。我錯過了什麼? – Moose 2012-02-02 15:54:30