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:
User
has_many :posts
end

Forum
has_many :posts
end

Post
belongs_to :forum
belongs_to :user
end

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] = @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
@current_user.posts

I followed an online tutorial for my user login.

I have the following method in my application controller

def current_user
session[:user]
end

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
session[:user]
end

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

and access user data like
current_user.posts

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
form?
For example, if I have a variable

@currentid = current_user.id

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

def create
@post = @forum.posts.build(params[: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:)