保存和检索模型

时间:2011-05-19 01:11:18

标签: ruby-on-rails ruby-on-rails-3

这似乎是一个初学者的问题,但它让我感到难过。我有一个用户模型和一个位置模型。位置属于用户,用户具有许多位置。我将位置存储为路由文件中的嵌套资源。

这是我的LocationsController文件中的create函数:

  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>

使用AJAX保存到数据库没有问题。但是,在检索记录时,返回表的最后一行仅包含用户名。不显示created_at,经度和纬度。如果我刷新页面然后显示它们。有没有人知道为什么会发生这种情况?

感谢。

更新

我颠倒了模型的顺序,它仍然是不打印的底部条目。我的猜测是它与视图而不是模型有关。

2 个答案:

答案 0 :(得分:1)

我认为在控制器中为AJAX响应初始化@locations变量时可能会出现问题。您保存新位置,但@user对象可能没有注意到。而不是

@locations = @user.locations

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

或类似的东西,这将保证您从数据库中提取位置。

这是一个猜测!

答案 1 :(得分:1)

由于您在保存新位置之前从数据库获取了用户记录,因此可能无法检索新位置。也许在渲染视图之前调用user.reload。或等到您保存位置之后再等User.find

相关问题