A
A
Art Snail2017-08-14 11:55:44
Ruby on Rails
Art Snail, 2017-08-14 11:55:44

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

2 answer(s)
A
Art Snail, 2017-08-14
@artsnail

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

A
Andrey Demidenko, 2017-08-14
@Dem1

current_user.answers.build(answer_params.merge(question_id: params[:question_id])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question