繁体   English   中英

将Ajax添加到Rails 3 form_for

[英]Adding ajax to Rails 3 form_for

我正在学习编程,并在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中呈现的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

不确定这是否是您create动作的完整代码段,但是您似乎正在尝试对不存在的实例变量调用render ... @profile从未在ObjectControllercreate方法中设置...

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

还请注意,在您现有的代码中,您正在调用render @profile.object ,但是Profile类与Object类具有has_many关系,因此,如果那是正确的代码,则应键入render @profile.objects (复数,不是单数)。

但是我想您可能想要上面提到的代码,因为您要追加到对象列表上,而不是再次渲染该列表?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM