Rails 4&控制器重定向路径

时间:2015-06-21 02:40:56

标签: ruby-on-rails

我正在尝试使用Rails 4创建一个应用程序,使用简单的表单形式。

我有一个叫做项目的模型和另一个叫做项目问题的模型。

关联是:项目有许多项目问题,并接受项目问题的嵌套属性。项目问题属于项目。

在我的项目问题表格中,我有:

 <%= 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" %>

在我的project_question控制器中,我有:

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

在我的项目控制器中,我将项目问题参数列入白名单,如下所示:

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

我的项目问题控制器也允许使用参数:

 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

在创建项目问题后,我无法确定如何在保存时重定向到项目页面。

1 个答案:

答案 0 :(得分:1)

首先,您需要使用

找到该特定项目
@project = Project.find(params[:project_id])

然后在你的创建控制器中,而不是写这两行

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

@project.project_questions.build(project_question_params)

然后在你的if语句中:

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

你很好!