0

我有一个没有主键的表,包含三列 - Player_ID、Season 和 Amount。当我想更新当前表时,出现以下错误消息:ActiveRecord::StatementInvalid (Mysql2::Error: Unknown column 'salaries.' in 'where clause': UPDATE salariesSET Season= 20192, Amount= 3232.0 WHERE salaries.`` IS NULL)

我的控制器中的更新方法:

def new
  @salary = Salary.new
  @players = Player.all
  @title = "Add salary"
end

def create
  @players = Player.all
  @salary = Salary.new(params[:salary])
  if @salary.save
    flash[:success] = "Successfully added salary"
    redirect_to salaries_path
  else
    @title = "Add salary"
    render 'new'
  end
end

def edit
  @player_id = params[:player_id]
  @season = params[:season]
  @salary = Salary.find_by_Player_ID_and_Season(params[:player_id], params[:season])
  @players = Player.all
  @title = "Edit salary"
end

def update
    @players = Player.all
    @player_id = params[:player_id]
    @season = params[:season]
    @salary = Salary.find_by_Player_ID_and_Season(params[:player_id], params[:season])
    if @salary.update_attributes(params[:salary])
       flash[:success] = "Successfully edited salary"
       redirect_to salaries_path
    else
       render 'edit'
    end
  end

_form.html.erb

<%= form_for(@salary, :url => salary_path(:player_id => @player_id, :season => @season)) do |f| %>
  <%= f.collection_select :Player_ID, @players, :ID, :Name %>
  <%= f.text_field :Season %>
  <%= f.text_field :Amount %>
  <%= f.submit "Add" %>
<% end %>
4

3 回答 3

1

Active Record 模型必须有一个主键,否则无法更新或删除行。

composite_primary_keys如果你真的不想在你的表中添加一个 ID 列,那么有一个宝石(尽管添加主键肯定是阻力最小的路径)

于 2012-10-07T15:22:00.207 回答
0

我知道您的错误的原因,尽管根本原因对我来说不是很清楚。您失败的查询是这样的:

ActiveRecord::StatementInvalid (Mysql2::Error: Unknown column 'salaries.' in 'where clause': UPDATE salaries SET Season = 20192, Amount = 3232.0 WHERE salaries.`` IS NULL)

重要的部分是:

WHERE salaries.`` IS NULL

WHERE salaries.foo IS NULL如果它是or会有一定的意义WHERE salaries.bar IS NULL,但你只是在列名通常存在的地方有空白。所以我猜MySQL(出于某种奇怪的原因)将其解释为您正在谈论一个名为salaries(ie salaries.salaries) 的列,该列不存在。

我什至不知道为什么该WHERE条款首先在那里。

你的create行动有效吗?

更新:问题几乎可以肯定是这一行:

if @salary.update_attributes(params[:salary])

我相信你想要的是:

if @salary.update_attributes(:amount => params[:amount])

看看有没有什么作用。

于 2012-10-07T12:38:06.710 回答
0

你的表已经有主键了!是id属性。params[:season]……我想是的,params[:salary][:season]对吧?我认为你应该用小写字母写season, player_id, amount。之后,如果仍然有问题,请在此处发布新代码^^

于 2012-10-07T12:06:51.833 回答