Rails Complex Form:选择和使用模板 [英] Rails Complex Form: selecting and working with templates
问题描述
class Project < ActiveRecord::Base
has_one :template
end
class Template < ActiveRecord::Base
belongs_to :project, foreign_key: "project_id"
belongs_to :admin
end
class Admin < ActiveRecord::Base
has_many :templates
end
鉴于我是用户,我想在创建新项目时选择一个模板.
Given I'm a user, I want to select a Template when creating a new Project.
然后我想编辑@project &@project.template 无需更改管理员的模板.
I then want to edit the @project & @project.template without changing the Admin's Template.
======问题========
======ISSUE========
我找不到显示如何操作的资源:
I haven't been able to find a resource that shows how to:
- 收集 Template.all 的 collection_select
- 将所选模板的属性(除了:id)传递给@project.build_template
- 创建与新项目关联的模板的新实例(包括关联和属性)
推荐答案
这是一种方法.首先,您需要在 Project new 操作中构建一个新模板.
Here is one way to do it. First, you need to build a new template in the Project new action.
template.build
然后添加collection_select.像这样:
Then add the collection_select. Something like this:
<%= f.collection_select(:random_virtual_attribute, Templates.all, :id, :name, {:include_blank => true}, {:multiple => false} ) %>
然后附加到选择上的更改事件.当它发生变化时,发出 JSON 请求以获取该特定模板.你可以使用respond_to和respond_with,http://davidwparker.com/2010/03/09/api-in-rails-respond-to-and-respond-with/.在 JSON 请求的回调中,设置您构建的模板的所有 fields_for.
Then attach to the change event on the select. When, it changes, make a JSON request to get that particular template. You can use respond_to and respond_with, http://davidwparker.com/2010/03/09/api-in-rails-respond-to-and-respond-with/. In the callback of the JSON request, set all of the fields_for of the template you built.
这篇关于Rails Complex Form:选择和使用模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!