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

Ruby on rails Rails:用于在创建新的子记录时选择现有父记录的表单?,ruby-on-rails,forms,associations,parent-child,Ruby On Rails,Forms,Associations,Parent Child,我有很多,属于两个模型之间建立的关联:项目和任务 我希望能够创建一个表单,使我能够创建一个新任务并将现有项目分配为父项目。例如,此表单可能有一个下拉列表,用于从现有项目列表中进行选择 这个应用程序中只有有限的一组可用项目,所以我通过seeds.rb文件创建了项目记录。我不需要创建新项目的表单 我相信我已经通过在新任务表单中使用collection\u selectform helper标记实现了一个解决方案。我对现在的工作方式很满意,但只是好奇是否有其他方法来解决这个问题 #models/pro

我有很多,属于两个模型之间建立的关联:项目和任务

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

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

我相信我已经通过在新任务表单中使用
collection\u select
form helper标记实现了一个解决方案。我对现在的工作方式很满意,但只是好奇是否有其他方法来解决这个问题

#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 %>
#models/project.rb
类项目:销毁
结束
#models/task.rb
类任务@task}
结束
结束
def创建
@task=task.new(参数[:task])
回应待办事项|格式|
如果@task.save
format.html{redirect_to(@task,:notice=>“任务已成功创建”)}
format.xml{render:xml=>@task,:status=>:created,:location=>@task}
其他的
format.html{render:action=>“new”}
format.xml{render:xml=>@task.errors,:status=>:unprocessable_entity}
结束
结束
结束
结束
#视图/new.html.erb
新任务


我刚刚查看了您的代码,这看起来很棒。一个小小的调整:

<%= f.collection_select(:project_id, Project.all, :id, :name) %>


这只是稍微简单了一点,因为您仍然在使用
|f |
块变量

,因为您提到了其他方法,我肯定会提到并推荐您使用。关联是自动处理的,可以保持代码的整洁,还可以提供一些很棒的定制选项

谢谢!我也在想办法摆脱这一行的任务。