jfalkson
jfalkson

Reputation: 3739

Rails 'best in place gem', update only one row

I am using the Best in Place gem with a rails 4 app, and have multiple records from a database table which is displayed to the user. Initially, my DB didn't update, but with Undefined method update_attributes? solution my DB now updates.

My current problem is: When the user edits a particular row, i want that row in the database to be updated. Right now the updated field causes all rows to be updated in the DB.

Here is the code for table which I want the user to edit that is rendered in the view:

<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>

Update action from controller:

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

This code is looping through each row exposed to the user and updating all the rows (instead of the one row in question), so I know why my current code is incorrect, but I am unsure how to fix this.

Can someone help me figure out how to only update the record being actively edited by the user?

Upvotes: 1

Views: 989

Answers (1)

Wally Ali
Wally Ali

Reputation: 2508

your update action should look like this:

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

only the params you pass in will be updated. Not necessary all of the params.

if you are editing, say, users show page, you'll change the above code to:

<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>

see here, you'll only be inline-editing the specific attributesthat you want to edit.

Upvotes: 2

Related Questions