通过AJAX将Rails变量传递给部分?

时间:2022-11-25 20:17:59

In my Rails app I'm passing a variable to this call: $.get("/parent_submissions/", {submission: d.id}, null, "script");, and I'd like the submission variable to pass through to the partial that is loaded through the controller. The controller action that is routed through /parent_submissions/ is:

在我的Rails应用程序中,我将一个变量传递给此调用:$ .get(“/ parent_submissions /”,{submission:d.id},null,“script”);,我希望提交变量通过到通过控制器加载的部分。通过/ parent_submissions /路由的控制器操作是:

def parent
    @submission = Submission.find(params[:submission])
end

That action loads parent.js.erb, which looks like this:

该操作加载parent.js.erb,如下所示:

$("body").append( "<%=j render :partial => 'parent', :locals => {:submission => @submission } %>" );

And _parent.html.erb simply looks like this:

_parent.html.erb看起来像这样:

<h1>@submission.title</h1>

I checked in my console to see what happens when the get request is called, and it looks like this:

我检查了我的控制台,看看调用get请求时会发生什么,它看起来像这样:

Processing by SubmissionsController#parent as JS
Parameters: {"submission"=>"190", "_"=>"1378443591336"}

This means that the submission value is not null, and is passing the correct submission id through the request correctly. But when the partial is rendered, it just looks like @submission.title.

这意味着提交值不为null,并且正确地通过请求传递正确的提交ID。但是当渲染部分时,它看起来像@ submission.title。

I assume something is wrong in the controller. Any ideas?

我假设控制器出了问题。有任何想法吗?

2 个解决方案

#1


3  

You need to change <h1>@submission.title</h1> to <h1><%= @submission.title %></h1> in your partial.

您需要在部分中将

@ submission.title 更改为

<%= @ submission.title%> 。

#2


1  

if your going to use the instance variable there is not reason for you to pass it in the locals hash.

如果您要使用实例变量,则没有理由在局部哈希中传递它。

So this line:

所以这一行:

$("body").append( "<%=j render :partial => 'parent', :locals => {:submission => @submission } %>" );

Could just be:

可能只是:

$("body").append( "<%=j render :partial => 'parent' %>" );

If you want to use the locals your partial needs to be the following:

如果您想使用本地人,您的部分需要如下:

<h1><%= submission.title %></h1>

#1


3  

You need to change <h1>@submission.title</h1> to <h1><%= @submission.title %></h1> in your partial.

您需要在部分中将

@ submission.title 更改为

<%= @ submission.title%> 。

#2


1  

if your going to use the instance variable there is not reason for you to pass it in the locals hash.

如果您要使用实例变量,则没有理由在局部哈希中传递它。

So this line:

所以这一行:

$("body").append( "<%=j render :partial => 'parent', :locals => {:submission => @submission } %>" );

Could just be:

可能只是:

$("body").append( "<%=j render :partial => 'parent' %>" );

If you want to use the locals your partial needs to be the following:

如果您想使用本地人,您的部分需要如下:

<h1><%= submission.title %></h1>