Mel
Mel

Reputation: 2685

Rails 4 & controller redirect path

I am trying to make an app with Rails 4, using simple form for forms.

I have a model called project and another model called project question.

The associations are: Project has many project questions and accepts nested attributes for project questions. Project questions belong to project.

In my project question form I have:

 <%= simple_form_for [@project, @project_question] do |f| %>
          <%= f.input :title, label: 'Question:',  :label_html => {:class => 'question-title'}, placeholder: 'Type your question here', :input_html => {:style => 'width: 100%', :rows => 4, class: 'response-project'} %>
          <%= f.input :content, label: 'Is there any context or other information?', :label_html => {:class => 'question-title'}, placeholder: 'Context might help to answer your question', :input_html => {:style => 'width: 100%', :rows => 5, class: 'response-project'} %>
  <br><br><br>
      <%= f.button :submit, 'Send!', :class => "cpb" %>

In my project_question controller, I have:

def create
    @project_question = ProjectQuestion.new(project_question_params)
    @project_question.project_id = project_question_params[:project_id]


    respond_to do |format|
      if @project_question.save
        format.html { redirect_to project_path(@project_question.project_id), notice: 'Project question was successfully created.' }
        format.json { render action: 'show', status: :created, location: @project_question }
      else
        format.html { render action: 'new' }
        format.json { render json: @project_question.errors, status: :unprocessable_entity }
      end
    end
  end

In my project controller, I have whitelisted the project question params as follows:

project_question_attributes: [:title, :content, :user_id, :project_id, :id,
      project_answer_attributes: [:answer, :project_question_id]],

The params are also permitted in my project question controller:

 def project_question_params
      params[:project_question].permit(:id, :title, :content, :project_id, :user_id,
      project_answer_atttibutes: [:id, :answer, :project_question_id, :user_id]
      )
    end

I am having trouble figuring out how to redirect to the project page on save after a project question has been created.

Upvotes: 0

Views: 124

Answers (1)

Ahmad Al-kheat
Ahmad Al-kheat

Reputation: 1795

First you would need to find that particular project using

@project = Project.find(params[:project_id])

Then in your create controller instead of writing these two lines

@project_question = ProjectQuestion.new(project_question_params)
@project_question.project_id = project_question_params[:project_id]

Write

@project.project_questions.build(project_question_params)

Then inside your if statement :

format.html { redirect_to @project, notice: 'Project question was successfully created.' }

And you are good!

Upvotes: 1

Related Questions