How to add signed in username to my model

I am new in Rails development, my first project is a simple website
where user can signed up and register for an event. I have created the
event model and used ‘devise’ for user model and authentication. I have
set the event.rb:

class Event < ActiveRecord::Base
has_many :user
end

and the user.rb:

class User < ActiveRecord::Base
belongs_to :event

Include default devise modules. Others available are:

:token_authenticatable, :encryptable, :confirmable, :lockable,

:timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable

Setup accessible (or protected) attributes for your model

attr_accessible :email, :password, :password_confirmation,
:remember_me
end

My question is how to add the current signed-in username to event model
relevant (participants) field.

Thank you in advance! Szabolcs

Well for starters, when you use a has_many argument you should be
passing the plural form of the model so…

has_many :users

Your user model would have to have an event_id as one of the fields so
it would have a relationship with your events table.

I would have written this completely different and reversed it by
stating that my users have many events. I would add a user_id to the
events table and then do the following in my events controller:

def new
@event = @current_user.events.new
end

This will automatically create a new event and insert the current user
id into the user_id field for you.

In the user model you could add:

has_many :events, :dependent => :destroy

This makes it so that if your user is deleted, the events associated
with that user are deleted as well.

And, then in the events model you would have:

belongs_to :user

… passing the model with singular…

Others may agree with your line of thought, but in this particular case,
I see the relationship reversed mainly because I read aloud the
belongs_to as:

Does my user belong to an event or does an event belong to my user.
Does my user have many events or do my events have many users. As you
can see, it sounds eerily similar. Or, does my event have a user or
does my user have an event. To me, in this particular case, I’d reverse
it. I don’t think there’s a wrong way of doing this one.

Also, you should read the devise wiki and github page as it states what
helper methods you have available. Since I don’t use devise, I’m still
fairly certain they have a current_user helper method for defining the
currently logged in user. In the controller you should be able to
access @current_user to find the currently logged in user.

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