I'm running into a problem when trying to create a new object using nested resources in Rails. My routing is set up as:
resources :coins do
resources :questions
end
When I attempt to create a new question, it does not save. I'm redirected to the 'questions' page and the form from the 'new' page including everything that was typed into it remains on the page (rather than the list of questions that are supposed to be there when it saves). My controller is as follows:
class QuestionsController < ApplicationController
before_action :find_question, only: [:show]
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(@question.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
My 'new' page then displays the following form:
<%= simple_form_for @question, url: coin_questions_path(@coin.id) do |f| %>
<%= f.input :ques_num %>
<%= f.input :content %>
<%= f.submit "Post", class: "btn btn-primary" %>
<% end %>
This is my first time using nested resources and its tripping me up a little bit. I really appreciate any assistance here.
@question.save!you will get error if there is any