例如,我有一个模型 Post
,其 bool 值称为 active
,我如何轻松地将这个值更改为 true
或 false
来自 index.html.erb 中的帖子列表,带有 link_to 或 button_to 帮助程序,如 remote: true
?
最佳答案
您可以获得一个 Controller 方法,例如toggle_active
来设置您的post
的active
状态,如下所示:
def toggle_active
@post = Post.find(params[:id])
status = !@post.active
@post.active = status
respond_to do |format|
if @post.save
render json: "success"
else
render json: "failure"
end
end
end
然后,在 routes.rb
中获取此操作的路由:
get 'post/:id/toggle-active' => 'post#toggle_active'
这应该给你一个toggle_active_post_path
或类似的东西。
这是您现在从 View 内部使用“button_to”或“link_to”定位的路径(视情况而定)。
<%= link_to "Activate/Deactivate", toggle_active_post_path(id: post.id), remote: true %>
是的,您设置了 remote: true
来启用 ajax 调用。
还有一件事:您需要定义一个相应的 toggle_active.js.erb
文件,来处理来自 ajax 的响应。
希望这有帮助...
关于javascript - rails 4 : change boolean value with ajax remotely,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33587338/