【问题标题】:Remove id from session hash Ruby on Rails从会话哈希 Ruby on Rails 中删除 id
【发布时间】:2015-07-01 22:57:14
【问题描述】:

我正在尝试从会话哈希中删除一个 id。我能够将 id 推送到 session[] 但现在当我尝试从散列中删除它时,它会从 camp.rb 模型中完整删除 id。我用脚手架创建了这个 rails 应用程序。有什么建议吗?

MODEL - cart.rb

class Cart

    def initialize(array_of_camp_ids = [])
        @camp_ids = array_of_camp_ids
    end

    def camps
        Camp.where(id: @camp_ids)
    end

_____________________________________________________________________


 applicaition_controller.rb

 class ApplicationController < ActionController::Base

  protect_from_forgery with: :exception
  before_action :set_cart

  private

  def set_cart
    session[:cart] ||= []
    @cart = Cart.new(session[:cart])
  end
end

_____________________________________________________________________

cart_controller.rb

def add_to_compare
  session[:cart] << @camp.id
  redirect_to '/compare'
end                     

_____________________________________________________________________

VIEW - camps.html.rb
<p>
  <strong>Name:</strong>
  <%= @camp.name %>
</p>

<p>
<%= form_tag(action: "add_to_compare") do %>
  <%= hidden_field :camp_id, value: @camp.id %>
<%= submit_tag "Add to comparison cart" %>
<% end %>
</p>

_____________________________________________________________________

VIEW - cart.html.erb

<tbody>
  <% @cart.camps.each do |camp| %>
    <tr>      
        <td><%= camp.name %></td>
        <td><%= link_to 'remove', camp, method: :delete, data: { confirm: 'Are you sure?' } %></td>     
    <tr>
      <% end %>
  </tbody>

【问题讨论】:

    标签: ruby-on-rails ruby session hash


    【解决方案1】:

    您的 link_to 正在您的购物车控制器上调用销毁操作。这将默认从数据库中删除。如果你不想这样做,你可以这样做session.data[:cart].delete @cart.id

    【讨论】:

    • 您好乍得,感谢您的回复。我对 RoR 比较陌生。我会把这个放在哪里?作为我的购物车控制器或购物车视图上的新操作?我都试过了,但我想我保存错了。
    • 如果您只是想从会话中删除它而不是从数据库中删除,您可以更改购物车控制器的销毁操作以执行我所说的操作。
    猜你喜欢
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 2017-10-27
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多