使用button_to链接到一个方法,可以这样做吗?

时间:2011-11-22 21:01:06

标签: html sql ruby-on-rails ruby

是否可以链接到不同模型中的方法?要按下按钮执行,还是有其他方法可以执行此操作,例如控制器中的操作?

员工模范内部的方法:

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

在不同模型的视图中:

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

1 个答案:

答案 0 :(得分:1)

Rails基于模型视图控制器模式(MVC)。这意味着,请求(例如通过浏览器)由您的控制器处理。控制器将从模型中收集所需的数据并将其传递给视图以供显示。

你可能的目标是:

路线:

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 %>