LandonSchropp
LandonSchropp

Reputation: 10234

Saving and Retrieving a Model

This might seem like a beginner question, but it has me stumped. I have a User model and a Location model. A location belongs to a user and a user has many locations. I have locations stored as a nested resource in my routes file.

Here's the create function in my LocationsController file:

  def create
    @user = User.find(params[:user_id])
    @location = @user.locations.build(params[:location])

    respond_to do |format|
      if @location.save
        format.html { redirect_to @user }
        format.js { 
          @locations = @user.locations
          render 'create' 
        }
      else
        format.html { render @user }
        format.js
      end
    end
  end

create.js.erb:

$('table#locations').html("<%= escape_javascript(render(@locations)) %>");

_location.html.erb:

<tr>
  <td><%= location.user.name %></td>
  <td><%= location.created_at %></td>
  <td><%= location.longitude %></td>
  <td><%= location.latitude %></td>
</tr>

Saving to the database using AJAX works without a problem. However, when the record is retrieved, the last row of the returned table only includes the user name. The created_at, longitude and latitude are not displayed. If I refresh the page then they are displayed. Does anybody have any ideas why this might be happening?

Thanks.

Update

I reversed the order of the models and it's still the bottom entry that isn't printing. My guess is it's something to do with the views and not the models.

Upvotes: 0

Views: 67

Answers (2)

Rob Sutherland
Rob Sutherland

Reputation: 1209

Since you're getting your user record from the database before saving the new location it might not be retrieving the new location. Perhaps a call user.reload before rendering the view. Or waiting to do User.find until after you've saved the location.

Upvotes: 1

CharlieMezak
CharlieMezak

Reputation: 5999

I think the problem may be arising when you initialize your @locations variable in the controller for the AJAX response. You save the new location, but perhaps the @user object doesn't notice. Instead of

@locations = @user.locations

try

@locations = Location.where(:user_id => @user)

or something like that, which will guarantee that you're pulling the locations from the database.

It's a guess!

Upvotes: 1

Related Questions