简体   繁体   English

Rails:使用JQuery而不是link_to进行发布请求

[英]Rails: Using JQuery for post request instead of link_to

Right now, there is a "votes" model in my Rails app. 现在,我的Rails应用程序中有一个“投票”模型。 Each post on a page has an upvote button, which is currently written as: 页面上的每个帖子都有一个upvote按钮,该按钮当前写为:

<%= link_to "✓", votes_path(:vote => {:post_id => post.id, :up => false}), :method => :post %>

Where post_id is the post that the vote is linked to and up is a boolean saying that the vote is true. 其中post_id是投票链接到上方的帖子,是布尔值,表示投票为真。 I'm trying to use JQuery instead of link_to so that the page doesn't reload every time someone votes. 我正在尝试使用JQuery而不是link_to,以便每次有人投票时都不会重新加载页面。 However, I don't understand what the AJAX post request looks like to interface with the database model. 但是,我不了解AJAX发布请求与数据库模型接口的外观。

Edit: Votes controller: 编辑:投票控制器:

def create
    respond_to do |format|
        format.html
        format.js { flash[:notice] = "Vote created"} # and render your <action>.js file}
    end
    @vote = Vote.where(:post_id => params[:vote][:post_id], :user_id => current_user.id).first
    if @vote
        @vote.up = params[:vote][:up]
        @vote.save
    else
        @vote = current_user.votes.create(vote_params)
    end 
    redirect_to :back
end

Use remote: true option for ajax call. 对ajax调用使用remote: true选项。

<%= link_to "✓", votes_path(:vote => {:post_id => post.id, :up => false}, :format => :js), :method => :post, remote: true %>

It will generate an ajax call to your controller. 它将生成对您的控制器的ajax调用。 You can then manipulate your action correspondingly. 然后,您可以相应地操作自己的动作。

respond_to do |format|
 format.html
 format.js { flash[:notice] = "Vote created"} # and render your <action>.js file
end

Update 更新

def create
    @vote = Vote.where(:post_id => params[:vote][:post_id], :user_id => current_user.id).first
    if @vote
        @vote.up = params[:vote][:up]
        @vote.save
    else
        @vote = current_user.votes.create(vote_params)
    end 
    respond_to do |format|
        format.html
        format.js { flash[:notice] = "Vote created"} # and render your <action>.js file}
    end
end

It should work, Let me know 它应该起作用,让我知道

And also check this.. 还要检查一下..

Your app/assets/javascripts/application.js should contain. 您的app/assets/javascripts/application.js应该包含。

//= require jquery 
//= require jquery_ujs

And your erb should contain 而且您的erb应该包含

<%= javascript_include_tag "jquery", "jquery_ujs" %>

You can reuse link_to to post a remote request without loading like: 您可以重复使用link_topost远程请求,而无需像这样加载:

<%= link_to "✓", votes_path(:vote => {:post_id => post.id, :up => false}), :method => :post, remote: true %>. 

You shall have to write a <your_action_name>.js.erb for the purpose though. 但是,您必须为此编写一个<your_action_name>.js.erb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM