【问题标题】:incorrect params in link_tolink_to 中的参数不正确
【发布时间】:2019-09-10 09:48:27
【问题描述】:

我想单击名为“用户”和“管理员”的下拉项,这应该会将我的帐户表中的角色列更新为该值。

      %tr
        %td 
          .dropdown
            %button#dropdownMenuLink.btn.btn-outline.btn-sm.dropdown-toggle{"aria-expanded" => "false", "aria-haspopup" => "true", "data-toggle" => "dropdown", :type => "button"}
              =account.role
            .dropdown-menu{"aria-labelledby" => "dropdownMenuButton"}
              .dropdown-item #{link_to "User", account.update_attribute("role", "user")} 
              .dropdown-item #{link_to "Admin", account.update_attribute("role", "admin")} 

我得到这个错误: undefined method `to_model' for true:TrueClass Did you mean? to_yaml

【问题讨论】:

  • update_attribute 方法返回truefalse,它不返回模型。此外,你为什么在你的视图中执行update_attribute而不是控制器,它应该在哪里?强烈反对。
  • 您是否知道link_to 方法和account.update_attribute 方法会在视图呈现时进行评估?此视图尝试首先将帐户的角色设置为“用户”,然后再设置为“管理员”。每次加载该页面时。

标签: ruby-on-rails ruby link-to update-attributes


【解决方案1】:

您需要在控制器中更新属性,而不是在视图中。您可以使用 link_to 进行操作并传递其他参数。

%tr
  %td 
    .dropdown
      %button#dropdownMenuLink.btn.btn-outline.btn-sm.dropdown-toggle{"aria-expanded" => "false", "aria-haspopup" => "true", "data-toggle" => "dropdown", :type => "button"}
        =account.role
      .dropdown-menu{"aria-labelledby" => "dropdownMenuButton"}
        .dropdown-item= link_to "User", path_to_your_action(id: account.id, role: :user) 
        .dropdown-item= link_to "Admin", path_to_your_action(id: account.id, role: :admin)

无论如何,您处理更新和重定向的控制器应该如下所示:

accounts_controller.rb

def your_action
  @account = Account.find(params[:id])
  if @account.update(role: params[:role])
    redirect_to # <somewhere>
  end
end

您最好使用form_for,而不是link_to

.dropdown-item
  = form_for account do |f|
    = f.hidden_field :role, value: :user
    = f.submit 'User'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 2020-03-13
    • 2021-01-11
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多