associations - Get id form another table, rails -
i have table test having fields 'user_id' , 'post_id'. user_id fetch current_user.id , post_id post table. 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 |format| @test.save format.html { redirect_to(:back, :notice => "successfull") } else format.html { render :action => "new" } end end
in models, create association:-
in test.rb:
belongs_to :post
in post.rb:
has_many :test
the view page is:
= form_for @test, :validate => true |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 post_id give error:
called id nil, mistakenly 4 -- if wanted id of nil, use object_id
how can resolve problem ?
is standard message in rails tells you tried invoke .id
on nil
value.
i suspect current_user
nil
. can sure raise current_user.inspect
think tell nil
you sure logged in current_user
not nil