Forum: Ruby on Rails Session is nil inside model

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Stuart G. (Guest)
on 2007-03-25 05:09
(Received via mailing list)
I'm tring to write a little function to indicate if a user is able to
pay an invoice, I have my invoice model with:

  def canPay?
    if session[:user].id == self.consumer_id
      return true;
    else
      return false;
    end
  end

as a method, but it gives the error:

"undefined local variable or method `session' for #<Invoice:
0xb7670928>"

Right before the method is called, I put a breakpoint, and session is
not nil, it has the user object in it as I expected it to.
Michael W. (Guest)
on 2007-03-25 06:28
(Received via mailing list)
Stuart G. wrote:
>
> as a method, but it gives the error:
>
> "undefined local variable or method `session' for #<Invoice:
> 0xb7670928>"
>
> Right before the method is called, I put a breakpoint, and session is
> not nil, it has the user object in it as I expected it to.

The session object is local to the controller (and the view rendered by
the controller). The simple workaround is to pass in session[:user] as a
parameter to canPay?


--
Michael W.
Ben M. (Guest)
on 2007-03-25 12:53
(Received via mailing list)
Michael W. wrote:
> Stuart G. wrote:
>> I'm tring to write a little function to indicate if a user is able to
>> pay an invoice, I have my invoice model with:
>>
> The session object is local to the controller (and the view rendered by
> the controller). The simple workaround is to pass in session[:user] as a
> parameter to canPay?


And the reason why the session is not available is that doing so would
break one of the core principles of the Model View Controller pattern:
the model should be completely unaware of the presentation layer.

You never want the model to use a session or an http request or generate
html. The model should contain your business data and the logic to
manipulate it.

Anyway, sorry to be pedantic, but that's why the session ain't
available... just pass the data you need to the method (or maybe some
earlier work that the controller does with the invoice model puts it
into a state where it is ready to answer the can_pay? message).

b
Stuart G. (Guest)
on 2007-03-25 15:50
(Received via mailing list)
On Mar 25, 9:52 am, Ben M. <removed_email_address@domain.invalid> wrote:

> Anyway, sorry to be pedantic, but that's why the session ain't
> available... just pass the data you need to the method (or maybe some
> earlier work that the controller does with the invoice model puts it
> into a state where it is ready to answer the can_pay? message).

Thanks Michael & Ben, makes perfect sense.
This topic is locked and can not be replied to.