1

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
1
  • Right now you're finding the @coin before all your actions. I don't think that's necessary :) Commented Jan 20, 2018 at 19:42

2 Answers 2

1

You could easily use hidden_field with a value - read more

For example:

<%= f.hidden_field :coin_id, value: @coin.id %>

And then the value will be in the params[:question][:coin_id] on create, so the rest should work as it is now. :)

Sign up to request clarification or add additional context in comments.

Comments

0

<%= hidden_field_tag(:coin_id, @coin.id) %> will generate a field with a name of just "coin_id"; you want "question[coin_id]"

You should, in turn, assign this value to the object in your controller. @question.coin_id = @coin.id, or @question = Question.new(:user => current_user, :coin => @coin) or @question = current_user.questions.new(:coin => @coin)

<%= f.input :coin_id, :as => :hidden %>

1 Comment

The input is missing the @coin.id.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.