Rails:在索引文件中使用PostController方法的正确方法 [英] Rails: Correct Way of Using the method of PostController in the Index file

查看:74
本文介绍了Rails:在索引文件中使用PostController方法的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学习如何使用索引页中控制器中定义的方法. 我正在尝试在博客上实现顶"按钮.

I'd like to learn how to use the methods defined in the controller in the index page. I'm trying to implement "like" button on my blog.

PostController

def like
@post = Post.find(params[:id])
@post.like += 1
@post.save
end

在列出所有帖子的索引中,我尝试过类似的操作.

In the index where all the posts are listed, I tried something like this.

<% @posts.each do |post| %>
 <tr>
  <td><%= post.name %></td>
  <td><%= post.created_at.strftime("%Y/%m/%d, %I:%M%p") %></td>
  <td><%= post.view %></td>
  <td><%= link_to 'like', like_post_path %></td>
  <td>hate</td>
</tr>
<% end %>

我通过查看代码了解了这个主意,

I got the idea by looking at the code,

<%= link_to 'make a new post', new_post_path %>
<%= link_to 'Edit', edit_post_path(post) %>

我认为在索引页的控制器中使用方法的方式是
(PostController中的方法)_post_path ,但看来我弄错了.

I thought the way to use methods in the controller in the index page was
(method in PostController)_post_path, but it seems I got it wrong.

undefined local variable or method `like_post_path'


我也试过像(post).


I've also tried like(post).

我的最终目标是使此函数成为ajax函数,所以我希望它是类似这样的形式

My ultimate goal is to make this function as an ajax function, so I expected it to be a form like

<% link_to_function 'like', like_post, remote: true %>

在这种情况下,使用"like"方法的正确方法是什么?

推荐答案

您需要定义一个命名路由才能完成此工作.喜欢:

You'd need to define a named route to make this work. Like:

# in config/routes.rb
resources :posts do
  member do
    get 'like'
  end

  # OR
  get 'like', :on => :member
end

# in `rake routes` this would show up as:
like_post GET    /posts/:id/like(.:format)  posts#like

# you'd reference in a view like:
like_post_path(@post)

这篇关于Rails:在索引文件中使用PostController方法的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆