Thông thường tôi sẽ không lưu trữ các đối tượng trong phiên Rails nhưng tôi đang sử dụng thư viện yêu cầu điều này. Tôi đã chạy vào một vấn đề rất lạ, nơi một đối tượng được lưu trữ xuất hiện như một String sau khi chuyển hướng.Đối tượng được lưu trong phiên Rails trở thành một String?
Để sinh sản tôi đã tạo ra một mẫu Rails 4.1 ứng dụng
$ rails new session-test
gia tăng một bộ điều khiển kiểm tra:
class HomeController < ApplicationController
def index
logger.debug "session[:customer]: #{session[:customer]}"
logger.debug "session[:customer].name: #{session[:customer].name}"
end
def from
Struct.new 'Customer', :name, :address
session[:customer] = Struct::Customer.new 'Dave', '123 Main'
redirect_to :action => :index
end
end
thiết lập các tuyến đường:
Rails.application.routes.draw do
get 'home/index'
get 'home/from'
root 'home#index'
end
Sau đó, tôi cháy lên Rails
$ bundle exec rails server
và nhấn localhost: 3000/home/từ trong trình duyệt:
Started GET "/home/from" for 127.0.0.1 at 2014-04-09 21:20:25 -0700
Processing by HomeController#from as HTML
Redirected to http://localhost:3000/home/index
Completed 302 Found in 18ms (ActiveRecord: 0.0ms)
Started GET "/home/index" for 127.0.0.1 at 2014-04-09 21:20:25 -0700
Processing by HomeController#index as HTML
session[:customer]: #<struct Struct::Customer name="Dave", address="123 Main">
Completed 500 Internal Server Error in 2ms
NoMethodError (undefined method `name' for "#<struct Struct::Customer name=\"Dave\", address=\"123 Main\">":String):
app/controllers/home_controller.rb:4:in `index'
Tôi không có ý tưởng tại sao đối tượng này là nhận được dịch là một String ...
Nó xuất hiện phải làm gì với loại cửa hàng phiên của cookie_store vì nếu tôi thay đổi
session_store.rb từ
Rails.application.config.session_store :cookie_store, key: '_session-test_session'
để
Rails.application.config.session_store :cache_store
nó hoạt động!
Bất kỳ ý tưởng nào?
Thư viện được đề cập là đá quý shopify_app được rất nhiều nhà phát triển sử dụng. Tôi đồng ý đó là một ý tưởng tồi để lưu trữ đối tượng trong phiên Rails vì một số lý do nhưng đó là những gì đá quý này làm: https://github.com/Shopify/shopify_app/blob/master/lib/generators/shopify_app/templates /app/controllers/sessions_controller.rb#L12-L13 Điều tôi đang băn khoăn là tại sao điều này lại bị bẻ cong trong Rails 4.1? Tôi không thấy nó xảy ra trong ứng dụng mẫu của họ là 3.2: https://github.com/Shopify/embedded-app-example –