Rails:用于在创建新子记录时选择现有父级的表单?

Cha*_*ory 8 forms ruby-on-rails parent-child associations

我在两个模型之间设置了has_many和belongs_to关联:Project和Task.

我希望能够创建一个表单,使我能够创建一个新任务并将现有项目指定为父项.例如,此表单可能具有下拉列表,用于从现有项目列表中进行选择.

此应用程序中只有一组有限的项目可用,因此我通过seeds.rb文件创建了项目记录.我不需要创建一个用于创建新项目的表单.

我相信我已经通过collection_select在新的任务表单中使用表单助手标记来实现解决方案.我对现在如何运作感到非常满意,但只是好奇是否有其他方法可以解决这个问题.

#models/project.rb
class Project < ActiveRecord::Base
  has_many :tasks, :dependent => :destroy
end

#models/task.rb
class Task < ActiveRecord::Base
  belongs_to :project
end

#controllers/tasks_controller.rb
class TasksController < ApplicationController

  def new
    @task = Task.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @task }
    end
  end

  def create
    @task = Task.new(params[:task])

    respond_to do |format|
      if @task.save
        format.html { redirect_to(@task, :notice => 'Task was successfully created.') }
        format.xml  { render :xml => @task, :status => :created, :location => @task }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @task.errors, :status => :unprocessable_entity }
      end
    end
  end
end

#views/new.html.erb
<h1>New task</h1>

<%= form_for(@task) do |f| %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="select">
    <%= collection_select(:task, :project_id, Project.all, :id, :name) %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

<%= link_to 'Back', tasks_path %>
Run Code Online (Sandbox Code Playgroud)

efa*_*cao 8

我刚刚审核了你的代码,这看起来很棒.一个小调整:

<%= f.collection_select(:project_id, Project.all, :id, :name) %>
Run Code Online (Sandbox Code Playgroud)

这只是稍微清洁,因为你仍在使用|f|块变量