繁体   English   中英

Rails 4和控制器重定向路径

[英]Rails 4 & controller redirect path

我正在尝试使用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

创建项目问题后,我很难弄清楚如何在保存时重定向到项目页面。

首先,您需要使用

@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.' }

而且你很好!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM