简体   繁体   中英

how to save a record in has many association in rails

I am working on a rails application, According to the requirement, I have to implement A team to which should add players, player has team id and user id. if I save user_id and team_id in players it is meant that one player is added to a particular team. I have user,team,player models. team has many players. player model contains user_id and team id. I am confused how to save records while adding players to team. I tried as

follows and added log as well.

//playercontoller:
     class PlayersController < ApplicationController
            def new
                @player= Player.new
                @team = Team.find(params[:team_id])
                @user=User.all
            end
            def create
                @team = Team.find(params[:player][:team_id])
                params[:players][:user_id].each do |user_id|
                @team.players.create(user_id: user_id)
                end
            end

    private

      def player_params
        params.require(:player).permit( :team_id,players[:user_id][]
                                     )
      end

    end

//new.html.erb

<div class="col-md-6 col-md-offset-3">
  <div class="container">
    <br>
    <h3>Add players to team <%= @team.team_name %></h3>
      <%= form_for @player do |f| %>
      <table>
        <tbody>
          <%= f.hidden_field :team_id, value: @team.id %>
          <tr>
            <th>Player Id</th>
            <th>Player Name</th>
            <th>Select</th>
          </tr>  
          <% @user.each do |x| %>
            <tr>
              <td><%= x.id %></td>
              <td><%= x.full_name %></td>
              <td><%= check_box_tag "players[:user_id][]",x.id %></td>
           </tr>
        <% end %>
        <tr>   
          <td>   
            <%= f.submit nil, class: 'btn btn-primary' %>
            <%= link_to t('.cancel', default:t("helpers.links.cancel")),
                root_path, class:'btn btn-default' %> 
           </td> 
          </tr>
        </tbody>
      </table> 
    <% end %>
  </div>
</div>
<%= will_paginate @user,renderer: BootstrapPagination::Rails,previous_label:"old",next_label: "new",inner_window:1,outer_window:1 %>             

log:

     Started GET "/" for 127.0.0.1 at 2019-02-27 10:06:36 +0530
       (0.3ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
      ↳ /home/sushmitha/.rvm/gems/ruby-2.5.1/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
    Processing by HomeController#home as HTML
      Rendering home/home.html.erb within layouts/application
      User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
      ↳ app/views/home/home.html.erb:3
       (0.2ms)  SELECT "roles"."name" FROM "roles" INNER JOIN "user_roles" ON "roles"."id" = "user_roles"."role_id" WHERE "user_roles"."user_id" = ?  [["user_id", 1]]
      ↳ app/models/user.rb:31
      Rendered home/home.html.erb within layouts/application (50.1ms)
      Rendered layouts/_header.html.erb (0.8ms)
      Rendered layouts/_footer.html.erb (0.3ms)
    Completed 200 OK in 328ms (Views: 310.2ms | ActiveRecord: 4.3ms)


    Started GET "/teams/1" for 127.0.0.1 at 2019-02-27 10:06:39 +0530
    Processing by TeamsController#show as HTML
      Parameters: {"id"=>"1"}
      User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
      ↳ /home/sushmitha/.rvm/gems/ruby-2.5.1/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
      Rendering teams/show.html.erb within layouts/application
      Team Load (0.4ms)  SELECT "teams".* FROM "teams"
      ↳ app/views/teams/show.html.erb:3
      User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 5], ["LIMIT", 1]]
      ↳ app/views/teams/show.html.erb:7
      User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 6], ["LIMIT", 1]]
      ↳ app/views/teams/show.html.erb:7
      User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 8], ["LIMIT", 1]]
      ↳ app/views/teams/show.html.erb:7
      User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 4], ["LIMIT", 1]]
      ↳ app/views/teams/show.html.erb:7
      User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 9], ["LIMIT", 1]]
      ↳ app/views/teams/show.html.erb:7
      User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 7], ["LIMIT", 1]]
      ↳ app/views/teams/show.html.erb:7
      Rendered teams/show.html.erb within layouts/application (33.7ms)
      Rendered layouts/_header.html.erb (0.9ms)
      Rendered layouts/_footer.html.erb (0.3ms)
    Completed 200 OK in 88ms (Views: 74.4ms | ActiveRecord: 3.7ms)


    Started GET "/players/new?team_id=11" for 127.0.0.1 at 2019-02-27 10:06:41 +0530
    Processing by PlayersController#new as HTML
      Parameters: {"team_id"=>"11"}
      User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
      ↳ /home/sushmitha/.rvm/gems/ruby-2.5.1/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
      Team Load (0.5ms)  SELECT  "teams".* FROM "teams" WHERE "teams"."id" = ? LIMIT ?  [["id", 11], ["LIMIT", 1]]
      ↳ app/controllers/players_controller.rb:4
      Rendering players/new.html.erb within layouts/application
      User Load (0.4ms)  SELECT  "users".* FROM "users" LIMIT ? OFFSET ?  [["LIMIT", 2], ["OFFSET", 0]]
      ↳ app/views/players/new.html.erb:15
       (0.2ms)  SELECT COUNT(*) FROM "users"
      ↳ app/views/players/new.html.erb:34
    /home/sushmitha/.rvm/gems/ruby-2.5.1/gems/will_paginate-bootstrap-1.0.1/lib/bootstrap_pagination/bootstrap_renderer.rb:11: warning: constant ::Fixnum is deprecated
      Rendered players/new.html.erb within layouts/application (35.9ms)
      Rendered layouts/_header.html.erb (0.9ms)
      Rendered layouts/_footer.html.erb (0.3ms)
    Completed 200 OK in 106ms (Views: 83.2ms | ActiveRecord: 2.7ms)


    Started POST "/players" for 127.0.0.1 at 2019-02-27 10:06:51 +0530
    Processing by PlayersController#create as HTML
      Parameters: {"utf8"=>"✓", "authenticity_token"=>"POfJTTsLKDZftZF1J4Rlj0Fc6Z5MxFM3gEhOTc4dv7m4neSK4oo4FTn+pSpuo09bEkAxPYu2ajqDsru/4fJgag==", "player"=>{"team_id"=>"11"}, "players"=>{":user_id"=>["1"]}, "commit"=>"Create Player"}
      User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
      ↳ /home/sushmitha/.rvm/gems/ruby-2.5.1/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
      Team Load (0.2ms)  SELECT  "teams".* FROM "teams" WHERE "teams"."id" = ? LIMIT ?  [["id", 11], ["LIMIT", 1]]
      ↳ app/controllers/players_controller.rb:14
    Completed 500 Internal Server Error in 9ms (ActiveRecord: 0.7ms)



    NoMethodError (undefined method `each' for nil:NilClass):

    app/controllers/players_controller.rb:15:in `create'

Without knowing the error, it's hard to fix the issue, but I don't think you need the [] before the .each . It should be:

@team = Team.find(params[:player][:team_id])
params[:players][:user_id].each do |user_id|
  @team.players.create(user_id: user_id)
end

It is good to indent your code correctly, it helps find errors and debug. Also, a form cannot be a child of a table unless it is within a th or td. The browser will place the form before of the table, but the fields within it therefore making the table empty:

<div class="col-md-6 col-md-offset-3">
  <div class="container">
    <br>
    <h3>Add players to team <%= @team.team_name %></h3>
      <%= form_for @player do |f| %>
      <table>
        <tbody>
          <%= f.hidden_field :team_id, value: @team.id %>
          <tr>
            <th>Player Id</th>
            <th>Player Name</th>
            <th>Select</th>
          </tr>  
          <% @user.each do |x| %>
            <tr>
              <td><%= x.id %></td>
              <td><%= x.full_name %></td>
              <td><%= check_box_tag "players[user_id][]",x.id %></td>
           </tr>
        <% end %>
        <tr>   
          <td>   
            <%= f.submit nil, class: 'btn btn-primary' %>
            <%= link_to t('.cancel', default:t("helpers.links.cancel")),
                root_path, class:'btn btn-default' %> 
           </td> 
          </tr>
        </tbody>
      </table> 
    <% end %>
  </div>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM