2016-08-17 6 views
0

Я создал игровой селектор для проекта фэнтези-футбола. Теперь, когда я пытаюсь сохранить команду, она просто откатывает фиксацию.Ошибка при сохранении в базе данных

HTML код команды:

<%= form_for(@team) do |f| %> 

         <center><h3>Choose your squad</h3></center> 
         <div class="col l5 offset-l1"> 
          <div class="row"> 
           <div class="input-field"> 
            <%= f.label :name %> 
            <%= f.text_field :name, required: true, :class => "validate", :placeholder => "Enter a name for your Team", :style => "width: 86%;" %> 
           </div> 
          </div> 
          <div class="row"> 
           <div id="playerCounter"> 
            <div class="col l6"> 
             <span id="playersAdded" >0</span>/<span id="totalPlayers" ></span> 
            </div> 
           </div> 

            <div class="hidden"> 
             <%= f.text_field :gk1_id, :id=>'contestEntry_goalkeeper1', :class=>"form-control" %> 
             <%= f.text_field :gk2_id, :id=>"contestEntry_goalkeeper2", :class=>"form-control" %> 
             <%= f.text_field :def1_id, :id=>"contestEntry_defender1", :class=>"form-control" %> 
             <%= f.text_field :def2_id, :id=>"contestEntry_defender2" , :class=>"form-control" %> 
             <%= f.text_field :def3_id, :id=>"contestEntry_defender3", :class=>"form-control" %> 
             <%= f.text_field :def4_id, :id=>"contestEntry_defender4", :class=>"form-control" %> 
             <%= f.text_field :def5_id, :id=>"contestEntry_defender5", :class=>"form-control" %> 
             <%= f.text_field :mid1_id, :id=>"contestEntry_midfielder1", :class=>"form-control" %> 
             <%= f.text_field :mid2_id, :id=>"contestEntry_midfielder2", :class=>"form-control" %> 
             <%= f.text_field :mid3_id, :id=>"contestEntry_midfielder3", :class=>"form-control" %> 
             <%= f.text_field :mid4_id, :id=>"contestEntry_midfielder4", :class=>"form-control" %> 
             <%= f.text_field :mid5_id, :id=>"contestEntry_midfielder5", :class=>"form-control" %> 
             <%= f.text_field :fwd1_id, :id=>"contestEntry_forward1", :class=>"form-control" %> 
             <%= f.text_field :fwd2_id, :id=>"contestEntry_forward2", :class=>"form-control" %> 
             <%= f.text_field :fwd3_id, :id=>"contestEntry_forward3", :class=>"form-control" %> 
            </div> 
            <div id="save-btn"> 
             <div class="col l6"> 
              <%= f.submit 'Save', :class =>"waves-effect waves-light btn orange accent-4" %> 

             </div> 
            </div> 



          <div class="col l3"> 
           <span>Remaining Salary</span> 
          </div> 
          <div class="col l3"> 
           <span id="salaryLeft" >100,000</span> 
          </div> 

          </div> 
         </div> 
        <% end %> 

Мой код контроллера:

class TeamsController < ApplicationController 
    before_filter :authenticate_user! 
    layout 'teams' 

    def index 

    @players = Player.all 


    end 

    def create 
    @players = Player.all 
    @team = Team.new(team_params) 

    if @team.save 
     redirect_to :index 
     flash[:notice] = "Team created successfully." 
    else 
     puts "error" 
     render :new 
    end 
    end 

    def new 
    @players = Player.all 
    @team = Team.new 
    end 

    def edit 
    @team = Team.find(params[:id]) 
    end 

    def update 
    @team = Team.find(params[:id]) 

    if @team.update_attibutes(team_params) 
     redirect_to :index 
     flash[:notice] = "Team updated successfully." 
    else 
     render :new 
    end 
    end 

    def show 
    @team = Team.find(params[:id]) 
    end 

    private 

    def team_params 

    params.require(:team).permit(:name, :gk1_id, :gk2_id, :def1_id, :def2_id, :def3_id, :def4_id, :def5_id, :mid1_id, :mid2_id, :mid3_id, :mid4_id, :mid5_id, :fwd1_id, :fwd2_id, :fwd3_id, :user_id) 

    end 
end 

Также консоль не отображает какую-либо ошибку. Мой журнал:

Started POST "/teams" for ::1 at 2016-08-17 04:51:59 +0530 
Processing by TeamsController#create as HTML 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"UU/L+RJgtQQQFy8o/bl8xucbPKGD6qTVfHPBCvsZIXx/VtRzm5zyPr24T0kdIcAXobO/gBpWNmY9G+pmKd3G8g==", "team"=>{"name"=>"Test Team", "gk1_id"=>"1", "gk2_id"=>"2", "def1_id"=>"5", "def2_id"=>"6", "def3_id"=>"7", "def4_id"=>"8", "def5_id"=>"9", "mid1_id"=>"26", "mid2_id"=>"20", "mid3_id"=>"19", "mid4_id"=>"18", "mid5_id"=>"17", "fwd1_id"=>"25", "fwd2_id"=>"24", "fwd3_id"=>"23"}, "commit"=>"Save"} 
    User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1 
    (0.2ms) BEGIN 
    Player Load (0.4ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 1 LIMIT 1 
    Player Load (0.3ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 2 LIMIT 1 
    Player Load (0.3ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 5 LIMIT 1 
    Player Load (0.3ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 6 LIMIT 1 
    Player Load (0.5ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 7 LIMIT 1 
    Player Load (0.3ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 8 LIMIT 1 
    Player Load (0.3ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 9 LIMIT 1 
    Player Load (0.3ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 26 LIMIT 1 
    Player Load (0.3ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 20 LIMIT 1 
    Player Load (0.3ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 19 LIMIT 1 
    Player Load (0.4ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 18 LIMIT 1 
    Player Load (0.3ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 17 LIMIT 1 
    Player Load (0.4ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 25 LIMIT 1 
    Player Load (0.3ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 24 LIMIT 1 
    Player Load (0.3ms) SELECT `players`.* FROM `players` WHERE `players`.`id` = 23 LIMIT 1 
    (0.2ms) ROLLBACK 
error 
    Rendering teams/new.html.erb within layouts/teams 
    Rendered devise/sessions/_new.html.erb (4.0ms) 
    Rendered devise/registrations/_new.html.erb (2.1ms) 
    Rendered shared/_navbar.html.erb (9.6ms) 
    Player Load (0.6ms) SELECT `players`.* FROM `players` 
    Rendered teams/new.html.erb within layouts/teams (26.7ms) 
Completed 200 OK in 87ms (Views: 38.8ms | ActiveRecord: 6.4ms) 

Я просто не могу понять проблему. Кажется, что все работает, оно принимает правильные значения, база данных подключена, пытаясь сохранить, но просто не сохраняет.

Любое предложение будет оценено по достоинству. Заранее спасибо. Кроме того, я совершенно новый с ROR, поэтому любая помощь в улучшении кода также была бы весьма признательна.

После Edit

Ok Теперь я изменил @ team.save на @ team.save !. Он показывает ошибку Ошибка: пользователь должен существовать.

И консоль показывает

Completed 422 Unprocessable Entity in 96ms (ActiveRecord: 7.2ms) 



ActiveRecord::RecordInvalid (Validation failed: User must exist): 

app/controllers/teams_controller.rb:16:in `create' 
    Rendering /usr/local/var/rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout 
    Rendering /usr/local/var/rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/_source.html.erb 
    Rendered /usr/local/var/rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (8.6ms) 
    Rendering /usr/local/var/rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb 
    Rendered /usr/local/var/rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.9ms) 
    Rendering /usr/local/var/rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb 
    Rendered /usr/local/var/rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (2.9ms) 
    Rendered /usr/local/var/rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (117.3ms) 

Мой код team.rb:

class Team < ApplicationRecord 
    has_many :players 
    belongs_to :user 
    belongs_to :gk1, :class_name => 'Player' 
    belongs_to :gk2, :class_name => 'Player' 
    belongs_to :def1, :class_name => 'Player' 
    belongs_to :def2, :class_name => 'Player' 
    belongs_to :def3, :class_name => 'Player' 
    belongs_to :def4, :class_name => 'Player' 
    belongs_to :def5, :class_name => 'Player' 
    belongs_to :mid1, :class_name => 'Player' 
    belongs_to :mid2, :class_name => 'Player' 
    belongs_to :mid3, :class_name => 'Player' 
    belongs_to :mid4, :class_name => 'Player' 
    belongs_to :mid5, :class_name => 'Player' 
    belongs_to :fwd1, :class_name => 'Player' 
    belongs_to :fwd2, :class_name => 'Player' 
    belongs_to :fwd3, :class_name => 'Player' 
end 
+1

В вашем 'commands_controller # create' метод измените' save' на 'save!', А затем повторно запустите его. Межбиблиотечная форма сохранения вызовет исключение из вашего журнала, чтобы мы могли видеть, что происходит. – MarsAtomic

+0

@ravi, можете ли вы разместить код в 'team.rb'? –

+0

@MarsAtomic - Done – Ravi

ответ

0

Я вижу, у вас есть связь, где team принадлежит к user, и, следовательно, ваш team объект должен иметь user_id атрибут. Однако, при попытке сохранить team объект в создании действия в ваших командах контроллерам, не связан с командой еще

Попробуйте сделать следующее в контроллере команд пользователя:

def create 
    @players = Player.all 
    @team = Team.new(team_params) 
    @team.user_id = current_user.id 

    if @team.save 
     redirect_to :index 
     flash[:notice] = "Team created successfully." 
    else 
     puts "error" 
     render :new 
    end 
end 
+0

Yeah thanx ... Я получаю это сейчас – Ravi

0

Вы имеете а так же user и teams, но вы создаете запись team, не связывая ее с user. Измените действие create, чтобы создать команду, связанную с записью user.

def create 
    @players = Player.all 
    @team = current_user.teams.new(team_params) 

    if @team.save 
    redirect_to :index 
    flash[:notice] = "Team created successfully." 
    else 
    puts "error" 
    render :new 
    end 
end 

Таким образом, когда team сохраняется, то user_id поле автоматически заполняется идентификатором current_user «s.

+0

Thanx много ... Я использую игроков для совершенно другой вещи ... Им не нужна доступность feild ... thanx anyways – Ravi

+0

@ravi, я неверно истолковал. Обновлен ответ. –