Rails'最好的地方gem',只更新一行

时间:2014-05-17 03:20:55

标签: ruby-on-rails ruby ruby-on-rails-4 best-in-place

我正在使用带有rails 4应用程序的Best in Place gem,并且从数据库表中有多条记录显示给用户。最初,我的数据库没有更新,但使用Undefined method update_attributes?解决方案我的数据库现在更新。

我当前的问题是:当用户编辑特定行时,我希望更新数据库中的该行。现在,更新的字段会导致所有行在数据库中更新。

以下是我希望用户在视图中呈现的表格代码:

<tbody>

<% @userdailydata.each do |data| %>
<tr>
<td> <%= best_in_place data, :date,:display_with => lambda { |v| v.strftime("%Y-%m-%d") }  %> </td>
<td> <%= best_in_place data, :calories_consumed %> </td>
<td> <%= best_in_place data, :calories_exercised %> </td>
<td> <%= best_in_place data, :weight %> </td>
</tr> 
<% end %>
</tbody>

从控制器更新操作:

def update
@userdailydata = Userdailydata.where(:user_id=>current_user.id)
respond_with @userdailydata
@userdailydata.each do |data|
   data.update_attributes(allowed_params)
end
end

此代码循环遍历用户的每一行并更新所有行(而不是所讨论的一行),因此我知道为什么我当前的代码不正确,但我不确定如何解决这个问题。

有人可以帮我弄清楚如何只更新用户主动编辑的记录吗?

1 个答案:

答案 0 :(得分:2)

您的update操作应如下所示:

def update
  @userdailydata = Userdailydata.find(params[:id]) #first, find the specific user by id
  #maybe, @userdailydata = Userdailydata.where(:user_id=>current_user.id) can replace the line above. they seem to be doing the same thing. 
  #the goal is fetch a specific user to edit it's attributes. 
  respond_to do |format|
    if @userdailydata.update(allowed_params) # i'm assuming you got allowed_params set up properly
       format.html { redirect_to @userdailydata }
       format.json { respond_with_bip(@userdailydata) }
   else
       format.html { render :action => "edit" }
       format.json { respond_with_bip(@userdailydata) }
   end
 end
end

只会更新您传入的参数。没有必要所有的参数。

如果您正在编辑,例如users show page,则您将上述代码更改为:

<tbody>


<tr>
<td> <%= best_in_place data @userdailydata, :date,:display_with => lambda { |v| v.strftime("%Y-%m-%d") }  %> </td>
<td> <%= best_in_place data @userdailydata, :calories_consumed %> </td>
<td> <%= best_in_place data @userdailydata, :calories_exercised %> </td>
<td> <%= best_in_place data @userdailydata, :weight %> </td>
</tr> 
</tbody>

请参阅此处,您只需内联编辑您要编辑的特定attributes