如何通过在链接中传递其ID来创建与另一个相关联的模型[Rails 4]

时间:2014-01-28 22:34:51

标签: ruby-on-rails ruby-on-rails-4

在我的项目展示视图中,我有一个按钮,用于创建与此项目关联的新问题,我将传递其ID。

<%= link_to 'Create question', new_question_path(:project_id => @project.id) %>

在我的问题控制器中我有set_project方法,它设置我在链接中传递的项目:

class QuestionsController < ApplicationController
 before_action :set_question, only: [:show, :edit, :update, :destroy]
 before_action :set_project, only: [:new, :create, :edit]
 before_action :set_categories, only: [:new, :edit]

 def new
  @question = Question.new
  @question.answers.build
  @project = Project.find(params[:project_id])
 end

 # GET /questions/1/edit
 def edit
 end

 # POST /questions
 # POST /questions.json
 def create
  @question = Question.new(question_params)
  @question.project = @project

 end

 # Never trust parameters from the scary internet, only allow the white list through.
 def question_params
  params.require(:question).permit(:question, :question_type,
                                   projects_attributes: [:id, :name, :category_id])
 end

 # now we are taking all projects, later we have to take the project correspondent (only one)
 def set_project
  #@project_options = Project.all.map{|p| [p.name, p.id]}
  if params[:project_id]
    @project = Project.find(params[:project_id])
  end
 end

 def set_categories
  @category_options = Category.all.map{|c| [c.name, c.id]}
 end
end

我的观点有点棘手,因为如果这个问题与新项目有关,我必须显示项目名称输入,用户也应该选择其类别,否则它只会显示项目名称。

<%= form_for(@question) do |f| %>
  <% if @project %>
    <div class="field">
        <label>Project Name</label><br>
        <%= @project.name %>
    </div>
  <% else %>
      <%= f.fields_for :projects do |project_form| %>
          <div class="field">
            <%= project_form.label :name, 'Project Name' %><br>
            <%= project_form.text_field :name %>
          </div>
           <div class="field">
             <%= project_form.label :category_id %><br>
             <%= project_form.select :category_id, @category_options %>
           </div>
      <% end %>
  <% end %>

  <div class="field">
    <%= f.label :question %><br>
    <%= f.text_area :question, rows: 3, cols:40 %>
 </div>
 <div class="field">
    <%= f.label :question_type %><br>
    <%= f.select :question_type, Question::QUESTIONS_TYPES, prompt: 'Select a question type' %>
 </div>

 <div class="actions">
   <%= f.submit %>
 </div>
<% end %>

即使我可以将问题提交到数据库,但相关的项目是零。任何有关如何使这项工作的建议都会非常有用。

由于

1 个答案:

答案 0 :(得分:0)

我认为你应该阅读rails指南的嵌套资源部分:

http://guides.rubyonrails.org/routing.html#nested-resources

基本上,您需要将嵌套资源添加到routes.rb文件中:

resources :projects do
  resources :questions
end

然后,您就可以链接到new的{​​{1}}操作,将QuestionsController传递给控制器​​:

project

然后在您的控制器中,您可以找到项目并为其创建一个新问题:

link_to 'New Question', new_project_question_path(@project)

阅读导轨指南 - 他们很好地解释了这些内容。