我正在尝试重写button_to

时间:2015-06-13 21:51:38

标签: ruby-on-rails ruby button-to

我正在尝试重写以下按钮代码,以便不是将我重定向到show页面,而是创建对象并保持显示当前页面。

<div class="colors">
    <li class="colors" id="greys">
        <%= button_to "some text", votes_path(color: 'grey', kid_id: current_kid, scoop_id: scoop.id, :method => :create), class: 'grey color-button' %>
    </li>
</div>

2 个答案:

答案 0 :(得分:3)

您应该使用远程标志通过javascript发送请求。并且可能会向用户提供反馈。

要通过rails中的js发送请求,您必须将remote: true添加到选项哈希:

<div class="colors">
    <li class="colors" id="greys">
        <%= button_to "some text", votes_path(color: 'grey', kid_id: current_kid, scoop_id: scoop.id, :method => :create), class: 'grey color-button', remote: true %>
    </li>
</div>

在您的控制器中,您可以通过回复js

来做出特殊回应
#votes controller
def create
  # ...
  respond_to do |format|
    format.js render
  end
end

在你的create.js.erb中,你可以使用embeded ruby​​编写javascript代码来提供响应。你甚至可以在这里渲染部分内容。

alert('create.js.erb')

答案 1 :(得分:0)

首先,为您的按钮添加一些id

<%= button_to "some text", votes_path(color: 'grey', kid_id: current_kid, scoop_id: scoop.id, :method => :create), class: 'grey color-button' id: 'buttonID' %>

然后,在您的Javascript代码中,每当单击该按钮时,向服务器发送请求,创建新记录,然后更新当前页面,以便显示已创建记录。

我会告诉你如何做的雕塑:

$("buttonID").click(function() {
    $.ajax({
        url: "some_url" // Your URL, for example, /votes
        type: "POST", // The type of request
        data: { color: "grey" } // Send data to server in this format
        success: function() {
            // Here you can update the page so that the user could
            // know the data has been posted, and no need to press 
            // the button again
        } 
    });
});