Ruby on Rails 中跨模型的 jQuery
我有一个相当简单的 Ruby on Rails 应用程序:两个模型 Lists
和 Items
。 Lists
有许多 Items
,并且 Items
属于 Lists
。好的。
ListsController
的 show
方法打印一个页面,其中包含属于给定列表的项目列表(在部分 lists/_listOfItems.html.erb
)。在 show.html.erb
视图的末尾,有一个表单可让用户将项目添加到列表中。在标准(无 jQuery)RoR 中,这非常有效。
现在,我想做的是让用户将项目添加到列表中,而无需重新加载页面。我已经使用 jQuery 将项目添加到数据库中,但现在我的问题是刷新 html 列表而不重新加载页面。我已经成功地在 ItemsController
中执行了 create.js.erb
,并且我可以使用它使内容显示在页面上,但问题是这个 create.erb
是这样创建的。 js.erb 位于 ItemsController
而不是 ListsController
中,因此如果我尝试使 create.js.erb
渲染部分_listOfItems.html.erb
,它将失败,因为 create.js.erb
位于 ItemsController
中,因此无法访问 中定义的变量
方法。ListsController
的 >show
我想如果我使用 ItemsController
的 index
方法来显示项目列表,它会像一个魅力,因为所有东西都在那里,但这可能会产生进一步的复杂性。
我希望这是清楚的。你能帮助我吗?非常感谢!
I have this rather simple Ruby on Rails application : two models Lists
and Items
. Lists
have many Items
and Items
belong to Lists
. OK.
The show
method of ListsController
prints a page with the list of the items belonging to the given list (in a partial lists/_listOfItems.html.erb
). At the end of the show.html.erb
view, there is a form that lets users add an item to the list. In standard (no jQuery) RoR, this works perfectly.
Now, what I want to do is let user add an item to the list without reloading the page. I have managed with jQuery to add the item to the database but now my problem is to refresh the html list without reloading the page. I have managed to have a create.js.erb
executed in ItemsController
and I can make things appear on the page with it but the problem is that this create.js.erb
lives in ItemsController
and not in ListsController
so that if I try to make create.js.erb
render the partial _listOfItems.html.erb
, it will fail since create.js.erb
lives in ItemsController
and hence cannot access the variables defined in the show
method of ListsController
.
I guess it would work like a charm if I was using the index
method of ItemsController
to display the list of items since everything would be living in there but that might yield further complications.
I hope that was clear. Can you help me? Thank you very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我理解正确,我认为解决方案在于 javascript + 控制器中的操作:
您的显示视图应该有一个 ajax 调用,如下所示,这应该由 click/change/... jquery 函数触发,例如: $( "selector").change(function() { 这里放置 ajax 调用 })
添加此 ajax 调用的 url 到您的路由,以便您的控制器响应
添加您的控制器操作,它应该触发渲染您想要的 html替换之前的 html。
If I understand right I think the solution lies in javascript + an action in your controller:
your show view should have an ajax call as follows, this should be triggered by a click/change/... jquery function, for example: $("selector").change(function() { here the ajax call is placed })
add the url that this ajax calls to your routes, so that your controller responds
add your controller action, it should trigger that renders the html that you want to replace the previous html with.