I am attempting to create a journal where a logged in user’s journal_entries are listed when the index view is called.
I have installed the Devise gem for the user sign up, log in/out authentication.
I have created a model, JournalEntries, which includes a date, string and text fields.
After creating the database, rake db:create and then migrating, rake db:migrate – I attempted to list a users journal entries in the journal_entries/index view. The default view that was derived via scaffolding lists ALL USERS journal_entries. This doesn’t make for a great journal – where you can see the entries of all other users.
In my research I’ve come to realize that I didn’t have a field in the journal_entries table which referenced the users table.
I create a migration show below:
class AddForeignKeyToJournalEntries < ActiveRecord::Migration
def up
change_table :journal_entries do |t|
t.references :user
end
#add a foreign key
execute <<-SQL
ALTER TABLE journal_entries
ADD CONSTRAINT fk_journal_entries_users
FOREIGN KEY (user_id)
REFERENCES users(id)
SQL
end
def down
execute <<-SQL
ALTER TABLE journal_entries
DROP FOREIGN KEY fk_journal_entries_users
SQL
end
end
(I also changed the users.rb and journal_entries.rb models to include belongs_to and has_many association – at first I thought this is all I had to do, and somehow the database would pick this up, but it didn’t…)
This successfully added foreign key – user_id to the journal_entries table, and I thought I was in the clear.
What is happening now is when a journal_entry is created – the user_id column is blank – no info is being populated there….? I have verified this by logging into Postgres on my local machine.
Any help would be greatly appreciated!
The reason the user_id column is blank in the journal_entry table is because you need to add the current user’s id when a new journal entry is created.
In your JournalEntries Controller you’ll need to add this to your create action:
@journal_entry.user_id = current_user.idor,
@journal_entry.user = current_userThen, in your JournalEntries Controller index action:
Instead of
@journal_entries = JournalEntry.allyou can display only the current logged in user’s entries with@journal_entries = current_user.journal_entries.Hope that helps!