我有一个没有主键的表,有三列 - Player_ID,Season和Amount。当我想更新当前表时,我有以下错误消息:ActiveRecord :: StatementInvalid(Mysql2 :: Error:未知列'工资。'in'where子句':UPDATE salaries
SET 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 %>
答案 0 :(得分:1)
Active Record模型必须有主键或行无法更新或删除。
如果您真的不想在表中添加ID列,则会有一个composite_primary_keys
gem(尽管添加该主键肯定是阻力最小的路径)
答案 1 :(得分:0)
你的桌子已经是主键了!这是id
属性。
params[:season]
...我认为它是params[:salary][:season]
,对吗?
我认为你应该写下小写season, player_id, amount
。之后,如果仍有问题,请在此处发布新代码^^
答案 2 :(得分: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
或WHERE salaries.bar IS NULL
,它会有一定的意义,但你只有一个空格,通常是列名。所以我猜MySQL(出于一些奇怪的原因)是解释这意味着你在谈论一个名为salaries
的列(即salaries.salaries
),它不存在。
我甚至不知道为什么WHERE
条款首先出现在那里。
您的create
行动有效吗?
更新:问题几乎可以肯定是这一行:
if @salary.update_attributes(params[:salary])
我相信你想要的是:
if @salary.update_attributes(:amount => params[:amount])
看看是否有任何作用。