Rails 3:jquery 更改部分
Rails 新手,我想了解一些有关 jquery 的知识,所以我想我会尝试使用 AJAX 在部分视图之间切换。
现在在我的用户的破折号上,我有一个指向他们的“喜欢”页面的链接,它需要完全重新加载才能看到“喜欢”页面,我如何更改它以使用 likes_user_path@user 刷新?
视图/页面/home.html.erb
<div id="left">
<div id="dash-statistics">
<a href="<%= likes_user_path(@user) %>">
<div id="likes" class="stat">Likes
<%= @user.likes.count %>
</div>
</a>
</div>
</div>
<div id="right">
<div id="content">
</div>
</div>
UsersController
def likes
@title = "Likes"
@user = User.find(params[:id])
@like_stuff = @user.likes.paginate(:page => params[:page])
render 'show_likes'
end
rails newbie herem, I'm looking to learn a little bit about jquery so I figured I'd try to switch between my partial views using AJAX.
Right now on my user's dash I have a link to their 'likes' page, it requires a full reload to see the 'likes' page, how would I change this to refresh with the likes_user_path@user)??
views/pages/home.html.erb
<div id="left">
<div id="dash-statistics">
<a href="<%= likes_user_path(@user) %>">
<div id="likes" class="stat">Likes
<%= @user.likes.count %>
</div>
</a>
</div>
</div>
<div id="right">
<div id="content">
</div>
</div>
UsersController
def likes
@title = "Likes"
@user = User.find(params[:id])
@like_stuff = @user.likes.paginate(:page => params[:page])
render 'show_likes'
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的理解是,您希望通过使用 ajax 在用户仪表板中单击链接来重新加载
likes
。首先要做的是重写链接,并添加
:remote =>; true
像这样:然后,在你的控制器中,确保顶部有一个
respond_to :html, :js
(当然可以有其他选项,但是:js
必须在其中)之后,您可以在控制器中执行一个名为
likes
的函数,用于加载喜欢的内容,它看起来像您的,只是您不这样做render
在最后,但是用@likes回复
。通过在respond_to
过滤器中添加:js
,Rails 将在需要时自动采取相应的行动。接下来,创建一个名为
likes.js.erb
的相应视图(我不确定咖啡脚本在这种情况下是否可以开箱即用),在其中放置类似的内容This 假设在您的 main 中您想要在其中呈现喜欢的视图,有一个带有
id=likes
的元素,可能如下所示:并且还有一个
_likes.html.erb
部分呈现喜欢和与我想我已经涵盖了这一点。
What I understand is that you want to reload the
likes
by clicking a link, by using ajax, in your user dashboard.First thing to do is rewrite the link, and add a
:remote => true
like this:Then, in your controller, make sure you have a
respond_to :html, :js
at the top (there can of course be other options, but:js
has to be among them)After that, you could do a function called
likes
in your controller which to use for loading the likes, which looks something like yours, only you don't dorender
at the end, butrespond_with @likes
. By having:js
in therespond_to
filter, Rails will automagically act accordingly when supposed to.Next, make a corresponding view called
likes.js.erb
(i'm not exactly sure if coffeescript will work out of the box in this case) in which you put something likeThis assumes that in your main view in which you want to render the likes ,there's an element with the
id=likes
which could look like this:and there's also a
_likes.html.erb
partial which renders the likesAnd with this I think I pretty much covered it.