Getting value from session - syntax help

Hi, I’m trying to make a rails app and although I understand the logic
of what I’m trying to do, the syntax used in ruby really confuses me as
it seems to do a lot of the work automatically.

I have 3 tables, user, forum and post. They are related as follows:
has_many :posts

has_many :posts

belongs_to :forum
belongs_to :user

When a user registers or logs in, the user is stored in a session. The
user can then add a post to a form by using the default form generated
by the scaffold. However, atm, the user can type in any user ID into
the form. I would like to delete this part of the form and use the
current [:user][:user_id] in it’s place but I don’t know how to combine
this with the already existing params in the controller.
Any advice would be appreciated, thanks in advance.

so you have something like this for login:

after finding user with name/pwd @user=User.find(…)
session[:user_id] =

and all following will just do:
@current_user = User.find(session[:user_id])

best to be placed in a before_filter

and access usert data like

I followed an online tutorial for my user login.

I have the following method in my application controller

def current_user

Then before_filter :current_user in my post controller…

I still don’t see how I can get the id and use it, sorry, the ruby
syntax just makes no sense to me :confused:

ok, this makes sense. most people store only the id in the session. in
your case it seems to store the whole user object. but that’s ok.

after finding user with name/pwd @user=User.find(…)
session[:user] = @user

this function simply returns this object (in Ruby you don’t need an
explicit return statement, whatever is in the last line will be
returned, session[:user] in that case)
def current_user

current_user will give you the whole user and you can get the id:

and access user data like

Hi again. Sorry to be a pain! I can access and display the values
fine, but how can I combine the value with the values obtained by the
For example, if I have a variable

@currentid =

How can I add it to the params in the create method of the controller?

def create
@post =[:post])

I apologise for being slow, but rails confuses me as it seems to do a
lot of the work for you, which is great if you understand it but bizzare
when you are trying to analyze things.

i don’t understand exactly, what you want, but in general:
params is a hash
to add something just do:
params[:key] = value

for a form you have a hash within a hash so you can do:
params[:post][:key] = value

so if i get it right you want to do something like
params[:post][:user_id] = @currentid

Thanks! I’ve got it working now:)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs