我正试图使用button_to助手远程更新我的数据库,尽管我遇到了一些问题,它似乎没有传递参数。
在我看来,我正在使用
- @availabilities.each do |a|
=button_to 'Accept', { :controller => 'availabilities', :action => :update, :id => a.id, :available => true }, :confirm => 'Are you sure?', :method => :post, :remote => true
并且在控制器中
# PUT /availabilities/1
# PUT /availabilities/1.json
def update
@availability = Availability.find(params[:id])
respond_to do |format|
if @availability.update_attributes(params[:availability])
format.html { redirect_to @availability, :notice => 'Availability was successfully updated.' }
format.js
else
format.html { render :action => "edit" }
format.js
end
end
end
控制台输出
Started POST "/availabilities/2/edit?available=true" for 127.0.0.1 at 2013-02-25 21:43:30 +1100
ActionController::RoutingError (No route matches [POST] "/availabilities/2/edit"):
看起来您已经设置了默认路由,该路由将POST
与控制器的创建操作相匹配,并拒绝任何用于更新现有对象的POST
数据。
在按钮的代码中,将方法更改为PUT
。
=button_to 'Accept', { :controller => 'availabilities', :action => :update, :id => a.id, :available => true }, :confirm => 'Are you sure?', :method => :put, :remote => true
注释讨论后的示例代码
在一个助手中,我有以下内容显示在视图中。
def toggle_admin(user)
if user.is_admin?
button_to "Yes", toggle_admin_path(user), :id => "toggle_admin_#{user.id}", :class => "btn btn-mini toggle-admin", :remote => true
else
button_to "No", toggle_admin_path(user), :id => "toggle_admin_#{user.id}", :class => "btn btn-inverse btn-mini toggle-admin", :remote => true
end
end
我的路由文件将toggle_admin_path
指向一个用户设置控制器,该控制器包含以下内容:
def toggle_admin
@user = User.find(params[:id])
@account = @user.account
if @user.is_admin? && @account.admins > 1
@user.remove_role :admin
else
@user.roles << :admin
end
if request.xhr?
render :status => 200, :content_type => 'text/javascript'
else
redirect_to edit_account_path
end
end