jeudi 27 août 2015

Rails- Removing items from a collection with checkbox form

I have a model called Teams, which has_many Tokens. On the show route for a particular team, I display all of its tokens, along with a checkbox. I want to be able to remove any number of tokens from the current team by checking the corresponding checkboxes and clicking "Save".

I have a pretty kludgey solution at the moment, in which:

All of the checkboxes are checked by default. A post action is made to teams_controller#remove_token, which extracts the values of boxes that have been unchecked, and then updates the team_id of the corresponding token to nil.

My kludge looks like this:

team.rb:

    has_many :tokens, inverse_of: :team

routes.rb:

     resources :teams do
       member do 
        post :remove_token

teams_controller.rb:

    def remove_token
        @team = Team.find(params[:id])
        tokens = params["tokens"].select {|k,v| v["team_id"] == "0"}

        tokens.each { |k,v| Token.find(k).update_attributes(:team_id => nil) }

        respond_to do |format|
          format.html {redirect_to team_url(@team) }
        end
   end

view:

   <%= form_tag remove_token_team_path do %>
        <% @team.account_tokens.each do |token| %>
                <%= token.email %>

                <%= fields_for "tokens[]", token do |f| %>
                    <%= f.check_box :team_id %>
                <% end %>
        <% end %>
        <%= submit_tag "Save"%> 
   <% end %>

The problems with this are that:

  • The checkboxes are all checked, and unchecking them removes the token from the collection. I want it to be the reverse.

  • Having to parse the params to read 0 values to select the tokens that should be removed from the collection seems like a pretty clumsy way to do this, but I haven't worked out a better one.

What is the correct way to remove multiple elements from a collection with Rails?




Aucun commentaire:

Enregistrer un commentaire