Answer the question
In order to leave comments, you need to log in
How to create and save an entry without hidden input?
Hello.
We have three tables users, questions, answers
users -> has_many questions & answers
questions -> has_many answers, belogs_to user
answers -> belongs_to user, belongs_to question
routes.rb
resources :questions do
resources :answers
end
answers_controller.rb
def create
@question = Question.find(params[:question_id])
@answer = @question.answers.build(answer_params)
if @answer.save
flash[:notice] = 'Your question has been successfully created'
redirect_to question_path(@question)
else
render 'questions/ show'
end
end
form for answer
= form_for [@question, @answer] do |f|
= f.label :body, 'Your answer'
= f.text_area :body, rows: 6
=
f.submit
'Reply' , but do not use it in the form
= f.hidden_field :user_id, value: current_user.id
I hope I was able to convey the essence of the question)
Answer the question
In order to leave comments, you need to log in
Got it ) thanks
answers_controller.rb
def create
@question = Question.find(params[:question_id])
@answer = @question.answers.build(answer_params)
if @answer.save
flash[:notice] = 'Your question was created successfully'
redirect_to question_path(@question)
else
render 'questions/show'
end
end
current_user.answers.build(answer_params.merge(question_id: params[:question_id])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question