【问题标题】:Rails: Using JQuery for post request instead of link_toRails:使用 JQuery 进行发布请求而不是 link_to
【发布时间】:2015-04-29 07:53:26
【问题描述】:

现在,我的 Rails 应用程序中有一个“投票”模型。页面上的每个帖子都有一个upvote按钮,目前写成:

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

其中 post_id 是投票链接到的帖子,up 是表示投票为真的布尔值。我正在尝试使用 JQuery 而不是 link_to,以便每次有人投票时页面都不会重新加载。但是,我不明白 AJAX 发布请求如何与数据库模型交互。

编辑:投票控制器:

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

【问题讨论】:

    标签: javascript jquery ruby-on-rails ajax


    【解决方案1】:

    使用remote: true 选项进行ajax 调用。

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

    它将生成对您的控制器的 ajax 调用。然后,您可以相应地操作您的操作。

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

    更新

    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
    

    应该可以,告诉我

    还要检查这个..

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

    //= require jquery 
    //= require jquery_ujs
    

    你的erb应该包含

    &lt;%= javascript_include_tag "jquery", "jquery_ujs" %&gt;

    【讨论】:

    • AJAX 请求似乎运行良好,但我对 respond_to 操作感到困惑。当我将它添加到投票控制器时,我收到以下错误消息:Missing template votes/create, application/create with {:locale=&gt;[:en], :formats=&gt;[:html], :variants=&gt;[], :handlers=&gt;[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}.
    • 这显然是指没有投票视图的事实,但它确实不应该寻找一个。我用我的投票控制器编辑了主要帖子
    • 你有你的动作的 html 视图文件吗?
    • ofc,format.js 应该处理请求。它不应该在寻找 html 文件
    • 它仍然给我同样的错误。 format.js 到底是什么?是要保存在视图中的 votes.js.erb 还是资产管道中的 votes.js 文件?
    【解决方案2】:

    您可以重复使用link_topost 的远程请求,而无需像这样加载:

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

    你必须为此写一个&lt;your_action_name&gt;.js.erb

    【讨论】:

      猜你喜欢
      • 2011-03-28
      • 2012-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-02
      • 2016-09-27
      • 2016-03-12
      • 1970-01-01
      相关资源
      最近更新 更多