如何从link_to调用操作

时间:2012-10-15 12:40:58

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我有索引页面users_controller:

  def index
    @companies = Company.where(:is_confirmed => "f")
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @companies }
    end
  end

我希望只需按一下按钮,公司就会将状态更改为已确认

   def confirm
    company = Company.find(params[:id])
    company.is_confirmed = "t"
    company.save
    redirect_to users_path
  end

按钮应该调用确认

= link_to '<i class="icon-ok icon-white"></i> '.html_safe + t('Confirm'), users_path, confirm: t('Are you sure'), :controller => "users", :action => "confirm", :class => 'btn btn-small btn-success'

请告诉我如何修复或告诉我哪里可以看到工作版

2 个答案:

答案 0 :(得分:3)

= link_to confirm_company_path(company), confirm: 'Are you sure', method: :post do
  %i{class: "icon-ok icon-white"}
  = t('Confirm')

在routes.rb

post '/company/:id/confirm' => "users#confirm", as: :confirm_company

1)更改对象时请勿使用GET请求,请改用POST

2)将确认逻辑移至公司模型并确认对公司控制器的操作

答案 1 :(得分:1)

您必须在controller / action / id参数和RESTful路由之间进行选择,请检查rails api。你可能想要这个:

= link_to '<i class="icon-ok icon-white"></i> '.html_safe + t('Confirm'), :controller => "users", :action => "confirm", :id => @companies, method: :post, confirm: t('Are you sure'), :class => 'btn btn-small btn-success'

= link_to '<i class="icon-ok icon-white"></i> '.html_safe + t('Confirm'), confirm_users_path(@companies), method: :post, confirm: t('Are you sure'), :class => 'btn btn-small btn-success'

暗示您的路线看起来像这样(RESTful):

resources :users do
  post 'confirm'
end

Yuri Barbashov是对的,这里的帖子更有意义。