开发者

Can I use Struct.new as a Rails model? Or: How to create anonymous structured non-db backed sessions?

Given the following example:

class AnonymousSession << Struct.new(:location, :preferences)
  def valid?
    ...
  end
  def new_record?
    ...
  end
end

While this interface is sufficient to create resourceful form and so on, it fails as soon as I want to save my form data to the session:

if session[:user] = AnonymousSession.create(params[:anonymous_session])
  #--> fails with开发者_运维百科 "unknown key(s): location..."
  ...
end

The error message is about "unknown keys". Any clue how to make it work? I just need anonymous sessions without database backend. They are completely disposable due to their short live nature.

Maybe my approach is wrong anyway and there's already an elegant solution to using anonymous sessions? I had a look at AuthLogic but any example I found always comes with an ActiveRecord model (and thus bound to a database).


I have used this solution, where my model derives from Tableless. I think it will work in your case as well.


Ryan Bates has a couple Railscast episodes that might help you out: Session Based Model and Super Simple Authentication.


You'd have to explain more as to what you're trying to accomplish. Why couldn't you just create an AnonymousSession class in /app/models?

class AnonymousSession

  attr_accessor :location, :preferences

  def new_record?
   # ...
  end

  def valid?
   # ...
  end

end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜