When creating a new model object using simple form, I need to pass the id of one object to the new object as it relies on the id for its URL. The routing is:
resources :coins do
resources :questions
end
I am attempting to do this using a hidden field tag but its not working. The ID is not passed and as a result, the new object does not save.
<%= simple_form_for @question, url: coin_questions_path(@coin.id) do |f| %>
<%= f.input :ques_num %>
<%= f.input :content %>
<%= hidden_field_tag(:coin_id, @coin.id) %>
<%= f.button :submit, 'Submit' %>
<% end %>
Prior to this, I was using collection_select in simple form to manually enter the ID and it worked, however I need it to happen automatically. Is there a better way of doing this that will do what I am looking for?
Question model:
class QuestionsController < ApplicationController
before_action :find_question, only: [:show, :edit, :update, :destroy ]
before_action :find_coin
before_action :authenticate_user!, except: [:index, :show]
def index
@questions = Question.where(coin_id: @coin.id).order("created_at DESC")
end
def show
end
def new
@coin
@question = current_user.questions.build
end
def create
@question = current_user.questions.build(question_params)
if @question.save
redirect_to coin_question_path(@coin.id, @question.id)
else
render 'new'
end
end
.
.
.
private
def find_question
@question = Question.find(params[:id])
end
def find_coin
@coin = Coin.find(params[:coin_id])
end
def question_params
params.require(:question).permit(:content, :ques_num, :coin_id)
end
end
@coinbefore all your actions. I don't think that's necessary :)