扶手:切换布尔州与的link_to [英] Rails: Toggle a Boolean State with a link_to

查看:97
本文介绍了扶手:切换布尔州与的link_to的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

添加一个管理员,以我的Rails应用(这一点: http://www.interque.co/ )。增加了一个布尔状态批准的每一个问题。我想通过点击我标记的批准链接切换的状态。

Added an admin view to my rails app (this: http://www.interque.co/). Added a boolean state for approved to each question. I'm trying to toggle that state by clicking a link I've labeled approved.

下面是我的控制器:

class AdminController < ApplicationController
  def index
    @questions = Question.all
    unless current_user && current_user.administrator?
        redirect_to root_path
    end
  end
end

下面是管理员认为我的工作,其中列出了所有未经批准的问题:

Here's the admin view I'm working with, which lists all unapproved questions:

<% if current_user %>
  <% @questions.each do |question| %>
    <% if question.approved == false %>
    <div>
        Title: <%= question.title %><br>
        Description: <%= question.description %><br>
        <%= link_to "Approve", question_path(question), :method => :put %>
    </div>
    <br>
    <% end %>
  <% end %>
<% end %>

我可以通过单击的link_to切换状态?我只需要设置question.approved =真。

Can I toggle the state by clicking a link_to? I just need to set question.approved = true.

任何帮助将是AP preciated。先谢谢了。

Any help would be appreciated. Thanks in advance.

推荐答案

远程地址:忠实于你的链接,并添加一个控制器动作,设置布尔状态。你可能要检查该链接改为批准后(包括在答辩)。另一个好处将是错误的情况下显示错误消息,并请求期间禁用链接。

Add remote: true to your link and add a controller action that sets boolean state. You'll probably want to check that link is changed to 'approved' after that (included in the answer). Another good thing will be displaying an error message in case of error and disabling link during request.

配置/ routes.rb中

config/routes.rb

resources :questions do
  member do
    put :approve
  end
end

意见/管理/ index.html.erb

views/admin/index.html.erb

<span class="approve-question">
  <%= link_to "Approve", approve_question_path(question), :method => :put, remote: true %>
</span>

意见/问题/ approve.js.erb

views/questions/approve.js.erb

$('.approve-question').html('Approved');

控制器/ questions_controller.rb

controllers/questions_controller.rb

respond_to :js

def approve
  @question = Question.find(params[:id])
  if @question.update(approved: true)
    render
  else
    render @question
  end
end

这篇关于扶手:切换布尔州与的link_to的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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