保存到数据库时出错

时间:2016-08-17 21:17:52

标签: ruby-on-rails activerecord crud

我为梦幻足球项目创造了一个球员选择器。现在,当我试图保存团队时,它只是回滚提交。

团队的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很新,所以在改进代码方面的任何帮助也将不胜感激。

编辑后

好的,我现在将@ 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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您与userteams之间存在关联,但您创建了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的ID。