[英]Rails: Form for selecting an existing parent when creating new child records?
I have a has_many and belongs_to association set up between two models: Project and Task. 我在两个模型之间设置了has_many和belongs_to关联:Project和Task。
I'd like to be able to create a form which enables me to create a new Task and assign an existing Project as a parent. 我希望能够创建一个表单,使我能够创建一个新任务并将现有项目指定为父项。 For example, this form might have a pulldown for selecting from a list of existing projects.
例如,此表单可能具有下拉列表,用于从现有项目列表中进行选择。
There are only a finite set of projects available in this application, so I've created Project records via a seeds.rb file. 此应用程序中只有一组有限的项目可用,因此我通过seeds.rb文件创建了项目记录。 I do not need to make a form for creating new Projects.
我不需要创建一个用于创建新项目的表单。
I believe I've achieved a solution by using a collection_select
form helper tag in the new Task form. 我相信我已经通过在新的任务表单中使用
collection_select
表单帮助器标记来实现解决方案。 I'm pretty happy with how this works now, but just curious if there are other approaches to this problem. 我对现在如何运作感到非常满意,但只是好奇是否有其他方法可以解决这个问题。
#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 %>
I just reviewed your code and this looks fantastic to me. 我刚刚审核了你的代码,这看起来很棒。 One small tweak:
一个小调整:
<%= f.collection_select(:project_id, Project.all, :id, :name) %>
This is just slightly cleaner in that you're still using the |f|
这只是稍微清洁,因为你仍在使用
|f|
block variable 块变量
Since you mentioned other approaches, I would definitely mention and actually recommend, you use formtastic . 既然你提到了其他方法,我肯定会提及并实际推荐,你使用formtastic 。 The associations are handled automatically and keeps your code clean and also gives you some great customization options.
这些关联会自动处理并保持代码清洁,并为您提供一些出色的自定义选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.