将ajax添加到Rails 3 form_for

时间:2011-10-18 16:17:03

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

我正在学习编程并在我的Rails 3应用程序中运行一个表单。现在我正在尝试向表单添加ajax,以便在提交后页面不会重新加载。

我已经按照了许多教程,但似乎无法弄清楚如何将它们结合在一起。该表单通过以下模型向Objects添加了新的Profile

class Profile < ActiveRecord::Base
  has_many :objects
end

class Object < ActiveRecord::Base
  belongs_to :profile
end

我的表单views/profiles/_object_form.html.erb

<%= form_for(@object, :remote => true) do |f| %>
<% end %>

在我的views/profiles/_about.html.erb中呈现表单及其创建的对象:

<div id="newObjects">
  <%= render :partial => 'object_form' %>
</div>
<div id="objectList">
  <%= render :partial => 'object', :collection => @profile.objects, :locals => {:object_count => @profile.objects.length) %>
</div>

在我的objects_controller.rb我有以下创建操作:

def create
  @object = Object.new(params[:object].merge(:author_id => current_user.id))
  respond_to do |format|
    if @object.save!
      format.html {redirect_to profile_path(@object.profile) }
      format.js { render }
    else
      format.html { redirect_to @profile, :alert => 'Unable to add object' }
    end
  end
end

views/objects/create.js.erb

$('#objectList').append("<%= escape_javascript(render @profile.object)) %>");

所以我有一个表单在另一个控制器中调用一个动作,我要添加ajax。目前发生的是我需要重新加载配置文件以显示新创建的对象。我做错了什么?

澄清:除了ObjectsController中的create动作外,我只在其他地方引用过@object。这是在ProfilesController的show动作中:

def show
  @profile = Profile.find(params[:id])
  @superlative = @profile.superlatives.new`
end

1 个答案:

答案 0 :(得分:0)

不确定这是否是您的创建操作的完整代码段,但看起来您正试图在不存在的实例变量上调用render ... @profile永远不会在{{create中设置1 {}}方法ObjectController ...

也许您打算输入$('#objectList').append("<%= escape_javascript(render @object)) %>");

另请注意,在您现有的代码中,您正在调用render @profile.object,但Profile类与您的Object类有一个has_many关系,所以如果这是正确的代码,然后你应该输入render @profile.objects(复数,而不是单数)。

但我认为您可能会想要我上面提到的代码,因为您要附加到对象列表中,而不是再次呈现列表?