从视图中更改布尔值

时间:2017-05-16 22:31:33

标签: ruby-on-rails ruby

我有一个模型organismereferent,它有一个名为active的布尔值。我想要做的是取决于它做了不同行动的价值。

因此,如果它处于活动状态,则按钮显示取消激活,并允许用户将active设置为false。所以在那之后按钮应该显示activate,这将允许用户将active设置为true。

我尝试在我的控制器中创建一个方法,然后从我的索引视图中调用该方法,但它给了我一个No route matches [POST] "/organismereferents/8"。我是Ruby on Rails的新手,所以必须有一种更简单的方法来实现它

查看:

<table class="table table-hover">

<tr>
    <th>Nom Organisation</th>
    <th>Site Web</th>
</tr>

<% @organismes.each do |organisme| %>
    <tr>
        <td><%= organisme.nom_organisation %></td>
        <td><%= organisme.site_web %></td>
        <td><%= link_to 'Show', organismereferent_path(organisme), class: 'btn btn-info' %></td>
        <td><%= link_to 'Edit', edit_organismereferent_path(organisme), class: 'btn btn-warning' %></td>

        <% if organisme.active == false %>

        <td><%= link_to 'Activate', organismereferent_path(organisme), class: 'btn btn-danger',
                method: :activate,
                data: { confirm: 'Are you sure?' } %></td>
        <% else %>

        <td><%= link_to 'Deactivate', organismereferent_path(organisme), class: 'btn btn-danger',
                method: :deactivate,
                data: { confirm: 'Are you sure?' } %></td>

        <% end %>

    </tr>
<% end %>
</table>

控制器:

def index
  @organismes = Organismereferent.all
end

def deactivate
  @organisme = Organismereferent.find(params[:id])
  @organisme.active = false
end

def activate
  @organisme = Organismereferent.find(params[:id])
  @organisme.active = true
end

如果您需要更多信息,我会很高兴添加它。

路线:

Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get 'master/index'

resources :organismereferents

# Notre page principal
root 'master#index'
end

enter image description here

1 个答案:

答案 0 :(得分:1)

我们在这里遇到一些问题。

首先,在您的观看中,sess.run(assignment, feed_dict={x: mnist.test.images[:1024], y: mnist.test.labels[:1024]})助手link_to参数并不想知道控制器操作的名称。它想知道要使用的http方法。对于您正在采取的行动,我认为最合适的是method。因此,将这些行更改为PATCH

其次,您需要更新method: :patch文件以包含所需的路由。您可以将routes.rb替换为以下内容来执行此操作:

resources :organismereferents

使用resources :organismereferents do member { patch :activate } member { patch :deactivate } end 标识向Rails表明您希望在URL中包含member param。现在,当您运行:id时,您应该看到以下内容:

rake routes

第三,你需要修复路径助手。 activate_organismereferents PATCH /organismereferents/:id/activate(.:format) organismereferents#activate deactivate_organismereferents PATCH /organismereferents/:id/deactivate(.:format) organismereferents#deactivate 返回的第一列告诉您可以在rake routes帮助程序中使用的Rails帮助程序路径的名称。因此,在您的激活链接中,您需要将link_to更改为organismereferent_path(organisme),并在停用链接中使用activate_organismereferent_path(organisme)

最后,在控制器操作中,更改布尔值后不会保存记录。您需要致电deactivate_organismereferent_path(organisme)以保留更改。或者,如果您希望进行更改并将其保存在一行中,则可以使用@organisme.save@organisme.update(active: true)