Reputation: 1113
I have a table test having fields 'user_id' and 'post_id'. user_id I fetch by current_user.id and post_id from the post table. For this I do: In test controller:-
def create
@user = current_user
@test = Test.new(params[:test])
@post = Post.find(params[:id])
@test.post_id = @post.id
@test.user_id = @user.id
respond_to do |format|
@test.save
format.html { redirect_to(:back, :notice => "successfull") }
else
format.html { render :action => "new" }
end
end
In my Models, I create association:-
In test.rb:
belongs_to :post
In post.rb:
has_many :test
The View page is:
= form_for @test, :validate => true do |f|
.span
= f.text_field :email, :placeholder =>"Email Address"
.span
= f.label :name
= f.text_field :name
.span
= f.submit "Save"
The user_id save properly but for post_id it give error:
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
How can I resolve that problem ?
Upvotes: 0
Views: 1300
Reputation: 47472
Are you sure you should access the create method only when you are login i.e. current_user should not be nil.
If you are getting this error in create
method only then it should be on line
@test.user_id = @user.id
this is because @user
is nil, and you are calling .id
on nil
.
EDITED
You need to send post_id from your form, assuming you are getting post object in @post
Add following line your view
= form_for @test, :validate => true do |f|
= hidden_field_tag "post_id", @post.id
and update
@post = Post.find(params[:id])
with
@post = Post.find(params[:post_id])
Upvotes: 1
Reputation: 7296
Is the standard message in Rails that tells you that you tried to invoke .id
on a nil
value.
I suspect your current_user
is nil
. You can be sure by raise current_user.inspect
i think which will tell you that its nil
You be sure you are logged in so that your current_user
is not nil
Upvotes: 1