2011-11-22 54 views
0

是否可以鏈接到不同模型中的方法?要按下按鈕執行,還是有另一種方式來做到這一點,就像控制器中的動作一樣?內的工作人員模型使用button_to鏈接到一個方法,可以做到嗎?

方法:

def clearleave 
self.where("grade = '1'").update_all(:leave_balance => 22) 
self.where("grade = '2'").update_all(:leave_balance => 25) 
self.where("grade = '3'").update_all(:leave_balance => 30) 
self.where("grade = '4'").update_all(:leave_balance => 35) 
end 

用於不同模型的圖內:在模型視圖控制器模式(MVC)

<%=button_to "Clear absences", {:controller => :staffs, :action => :clearleave} %> 

回答

1

Rails的鹼基。這意味着請求(例如通過瀏覽器)由您的控制器處理。控制器將從模型中收集所需的數據並將其傳遞給視圖進行顯示。

你可能瞄準什麼是這樣的:

路線:

resources :staff do 
    member do 
    post :clearleave 
    end 
end 

控制器:

# StaffController 
def clearleave 
    @staff = Staff.find(params[:id]) 
    @staff.clearleave # this calls the method in your model 
    # here you could redirect to e.g. the show page for your staff 
    # redirect_to staff_path(@staff), :notice => "Cleared successfully" 
end 

您的視圖按鈕將是:

<%= button_to "Clear absences", clearleave_staff_path(@staff) %> 
<!-- not sure if a ", :method => :post" is required here as well --> 
<!-- in rails 3 a link_to should also work --> 
<%= link_to "Clear absences", clearleave_staff_path(@staff), :method => :post %> 
+0

最有用的,謝謝 – arcanine

相關問題