Valit Laiho
Valit Laiho

Reputation: 29

incorrect params in link_to

I want to click on dropdown item called "User" and "Admin" and this should update role column in my account table to this value.

      %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")} 

And I get this error: undefined method `to_model' for true:TrueClass Did you mean? to_yaml

Upvotes: 0

Views: 48

Answers (1)

Yury Matusevich
Yury Matusevich

Reputation: 998

You need to do update of attributes in controller, not in views. You can use link_to to go to an action and pass additional params.

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

Anyway your controller to handle update and redirect should look like:

accounts_controller.rb

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

instead of link_to, you'd better use form_for.

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

Upvotes: 0

Related Questions