2013-03-10 42 views
0

我有2个模型 - 安排和联系。Rails试图在ajax调用后重新加载数据

在我/views/arrangements/index.html.erb页,我想展现的联系人表。

我也有这种形式在它在我的安排一个示范窗口/ index.html.erb

<%= form_for @new_to_contact, :remote => true, :id => 'new_item' do |f| %> 
    <%= f.label :family_name %> 
    <%= f.text_field :family_name %> 
    <%= f.label :action %> 
    <%= f.text_area :action, :rows => 3 %> 
    <%= button_tag "Save", :type => 'submit' %> 
    <%= button_tag "Cancel", :type => 'button', :data => {:dismiss => 'modal' } %> 
    <% end %> 

这里是我的arrangements_controller#index方法

def index 
    @arrangements = Arrangement.find(:all, :order => 'location_id') 
    @new_to_contact = Contact.new 

    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render json: @arrangements } 
    end 
    end 

这里是我的contacts_controller#create方法

def create 
    @to_contact = Contact.new(params[:to_contact]) 

    respond_to do |format| 
     if @to_contact.save 
     format.js 
     format.html { redirect_to @to_contact, notice: 'To contact was successfully created.' } 
     format.json { render json: @to_contact, status: :created, location: @to_contact } 
     else 
     format.html { render action: "new" } 
     format.json { render json: @to_contact.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

这是我/views/contacts/create.js.erb

console.log('TEST'); 
$('#myModal').modal('hide'); 

我的问题是,我该如何重装我的联系人列表中的我的安排索引文件从我create.js.erb文件?

我想加入这行来我create.js.erb文件,但扔了模板错误:

$(".table").html("<%= escape_javascript(render(Contact.all)) %>"); 

回答

1

根据Rails的方式,你应该提取的安排/索引你的new_contact形式.html.erb添加到contacts/_form.html.erb并呈现这部分内部安排/ index.html.erb。

然后你就可以轻松地从js.erb文件中使用像渲染这个模板:

$('.table tr:last').after("<%= escape_javascript(render :partial => 'form', :locals => {:contact => @to_contact}) %>") 
+0

我之所以在安排new_contact形式/ index.html.erb是因为我想有一个模式窗口,他们可以在排列页面上添加新联系人,而无需转到联系人页面,添加联系人,然后返回安排页面。 – Catfish 2013-03-10 17:03:07

+0

好吧,我创建了一个名为views/contacts/_running_list.html.erb的部分,并将我的表单代码移动到该部分。当我尝试添加一个新的联系人时,我收到错误“未定义的方法”为空? for nil:NilClass'在_running_list部分的这一行上<%if to_contacts.empty? %>' – Catfish 2013-03-10 17:21:28

+0

因为你现在正在从JS局部渲染,所以你必须使用定义为局部变量的变量而不是控制器动作中定义的实例变量。实例变量当然可以在您的JS.erb模板中使用。所以,尝试通过这个当地人在你的电话渲染:部分 – Nerve 2013-03-10 19:10:13

相关问题