This is a newbie question, but I\'m still learning how to create an association between two models in rails. I have a user model and a journal_entry model. The journal entri
Ok, so I got this working by adding the user to the create action in my journal_entries_controller.rb. Here's the code I used, but is this the "rails way" to do this?
def create
@user = current_user
@journal_entry = @user.journal_entries.build(params[:journal_entry])
if @journal_entry.save
flash[:success] = "Journal entry created!"
end
end
i bet, that u forget something like
def create
@journal_entry = @user.journal_entries.build(params[:journal_entry])
# @journal_entry = current_user.journal_entries.build(params[:journal_entry])
if @journal_entry.save
..
you have it right this time. You added the user association to the journal model which loads the user in the controller before displaying it in the view. You do need the hidden fields in your form which you added, since you are using a stateless protocol. On the update/create action, double check that the user posting is the user using and save.
journal_entry model should look like
class JournalEntry < ActiveRecord::Base
attr_accessible :post, :title, :user_id
belongs_to :user
validates :user_id, presence: true
default_scope order: 'journal_entries.created_at DESC'
end
This should work!
You need to add user_id to your attr_accessible
call, if you look at your logs it is probably warning you that it can't mass assign it.