我正处于创建应用程序的早期阶段,只是放置了一些基本的代码.这是当前的代码…
应用程序/视图/卡/ front.html.erb
<%= form_for(front_of_card_path) do |f| %> <%= f.fields_for :competency_templates do |builder| %> <%= render 'add_fields',f: builder %> <% end %> <%= link_to_add_fields "Add New Tag",f,:skill %> <% end %>
路线
controller :cards do get '/front',action: 'front',as: 'front_of_card' post '/save',action: 'create',as: 'save_card' get '/my_contact_info',action: 'back',as: 'back_of_card' put '/save',action: 'update',as: 'save_card' get '/my_card',action: 'show',as: 'card' end
调节器
def create @skill= Skill.new(params[:skill]) @tag = Tag.new(params[:tag]) @tag.save @skill.tag_id = @tag.id @skill.save redirect_to front_of_card_path,notice: 'Skill was successfully created.' #get user/session #save skills & tags end
cards.js.coffee
jQuery -> $('form').on 'click','.remove_fields',(event) -> $(this).prev('input[type=hidden]').val('1') $(this).closest('fieldset').hide() event.preventDefault() $('form').on 'click','.add_fields',(event) -> time = new Date().getTime() regexp = new RegExp($(this).data('id'),'g') $(this).before($(this).data('fields').replace(regexp,time)) event.preventDefault()
app_helper
module ApplicationHelper def link_to_add_fields(name,association) new_object = f.object.send(association).klass.new id = new_object.object_id fields = f.fields_for(association,new_object,child_index: id) do |builder| render(association.to_s.singularize + "_fields",f: builder) end link_to(name,'#',class: "add_fields",data: {id: id,fields: fields.gsub("\n","")}) end end
所以现在这个代码给了我两个文本字段.一个用于标签名称,另一个用于标签权重,并且控制器将所有内容插入数据库.我想使用一些JavaScript来动态地添加我喜欢的这些标签/权重字段中的许多.我发现的一切似乎都集中在嵌套的属性上.任何想法赞赏
更新
添加了更多的代码来肉体这一点.我遇到的问题是我在这行上传过的第三个变量
<%= link_to_add_fields "Add New Tag",:skill %>
它不喜欢’:技能’,但我不知道我应该在这里经过.
解决方法
所以这里是我想出来的…这里是我的两个模型…
class Skill < ActiveRecord::Base belongs_to :tag attr_accessible :tag_id,:weight end class Tag < ActiveRecord::Base has_many :skills attr_accessible :name end
我从app / views / skills / _form.html.erb中调用部分内容,并使用js标签添加新字段.还要注意,我正在重新渲染部分,然后将其隐藏在最后一个div标签中.
<div id="skillSet"> <%= render partial: "skills_form" %> </div> <a href="javascript:;" id="addNewTag">Add New Tag</a> <div class="actions"> <%= f.submit %> </div> <% end %> <div class="hide" id="new_skills_form"> <%= render partial: "skills_form",locals: {skill: false} %> </div>
部分很简单.我在这里所做的只是将值存储在数组中…
<div class="skillsForm"> <%= label_tag 'tag' %> <%= text_field_tag 'tags[]' %> <%= label_tag 'weight' %> <%= text_field_tag 'weights[]' %> </div>
…这里是javascript …真正的直接,只是说当#addNewTag被点击,appeand #new_skills_form到#skillSet
$(document).ready(function(){ $("#addNewTag").click(function(){ $("#skillSet").append($("#new_skills_form").html()); }); });
…最后控制器动作解除了数组的管理,并保存了它们…
def create @skill = Skill.new(params[:skill]) tags = params[:tags] weights = params[:weights] tags.each_with_index do |tag,index| tag = Tag.create :name => tag Skill.create :tag_id => tag.id,:weight => weights[index] end end