【问题标题】:jQuery TokenInput plugin with deep nested_attributes pre-populating tokens on edit具有深度嵌套属性的 jQuery TokenInput 插件在编辑时预填充标记
【发布时间】:2012-06-06 16:41:51
【问题描述】:

我的应用程序具有以下结构。

class Foo < ActiveRecord::Base
  has_many :examples, :dependent => :destroy

  accepts_nested_attributes_for :examples
end

class Example < ActiveRecord::Base
  belongs_to :foo
  has_many :codes, :dependent => :destroy

  accepts_nested_attributes_for :codes, :reject_if => lambda { |a| a[:code].blank? }
end
class Code < ActiveRecord::Base
  belongs_to :example
  has_many :code_kinds
  has_many :kinds, :through => :code_kinds
  attr_reader :kind_tokens

  def kind_tokens=(ids)
    self.kind_ids = ids.split(",")
  end
end
class CodeKind < ActiveRecord::Base

  belongs_to :code
  belongs_to :kind

end
class Kind < ActiveRecord::Base
    has_many :code_kinds
    has_many :codes, :through => :code_kinds   
end

它在创建和保存时非常适合带有fields_for 的表单。

我正在使用kind_tokens,如RailsCast #258 Token Fields 所述

但是在编辑表单上,现在一切都完美显示了,我应该在examplescode 的嵌套属性内的kind_tokens 字段中预先填充data-pre 属性中的数据。

RailsCast 说:

<%= f.text_field :author_tokens, "data-pre" => @book.authors.map(&:attributes).to_json %>

但我不能这样做 @foo.examples.codes.kinds.map... 因为与 Fooexamples 的关系返回一个集合,与 codes 的情况相同。

我只是在使用:

&lt;%= f.fields_for :codes do |codes_form| %&gt;

在里面

&lt;%= f.fields_for :examples do |examples_form| %&gt;

现在,如果我没有任何循环,并且一切都由 nested_attributesfields_for 完成,我该如何为代码预填充类型?

【问题讨论】:

    标签: ruby-on-rails-3 activerecord nested-attributes jquery-tokeninput


    【解决方案1】:

    已解决

    每次使用

    &lt;%= f.fields_for ...

    Rails 会自动生成 loop,因此您可以在其中设置某种计数器,例如:

    <%
    @ctrEx = 0
    @ctrCd = 0
    %>
    <%= form_for @foo ...
        <%= f.fields_for :examples do |examples_form| %>
            ...
    
            <%= examples_form.fields_for :codes do |codes_form| %>
                ...
                <%= codes_form.text_field :kind_tokens, :class => "tag_matcher", "data-pre" => @foo.examples[@ctrEx].codes[@ctrCd].kinds.map(&:attributes).to_json %>
                ...
                <%@ctrCd +=1%>
            <%end%>
    
            ...
            <%
            @ctrEx += 1
            @ctrCd = 0
            %>
        <%end%>
    <%end%>
    

    现在您可以像这样在data-pre 中使用您的计数器:

    @foo.examples[@ctrEx].codes[@ctrCd].kinds.map(&:attributes).to_json
    

    我是这么想的,但肯定还有别的办法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-09
      • 2016-06-02
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多