我使用以下代码在视图中创建下拉列表以将模型与另一个模型相关联。这有效但我必须预先填充数据库中的任务。我希望能够在创建项目期间创建任务,而不是仅选择已经存在的任务。
<%= f.label :task %>
<%= f.collection_select( :task_id,
Task.all,
:id, :name, {selected: @project.task_id, include_blank: false}) %>
根据我的理解,我也必须在控制器中执行此操作,但我见过的很多代码都已过时,我想以Rails 4的方式执行此操作。谢谢!
答案 0 :(得分:1)
如果你正在创建一个新项目&amp;尝试创建任务时,您需要使用nested model form
(accepts_nested_attributes_for
):
#app/models/Project.rb
def Project < ActiveRecord::Base
has_many :tasks
accepts_nested_attributes_for :tasks
end
#app/controllers/projects_controller.rb
def new
@project = Project.new
@project.tasks.build #-> do this for as many tasks as you want
end
def create
@project = Project.new(project_params)
@project.save
end
private
def project_params
params.require(:project).permit(:new, :project, :attrs, tasks_attributes: [:task_name])
end
#app/views/projects/new.html.erb
<%= form_for @project do |f| %>
<%= f.text_field :name %>
<%= f.fields_for :tasks do |t| %>
<%= t.text_field :name %>
<% end %>
<% end %>