【问题标题】:Add extra result to Association Collection Proxy result将额外结果添加到关联集合代理结果
【发布时间】:2015-07-08 11:44:18
【问题描述】:

我有两个模型,

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to: user
end

我正在使用formtastic gem,请考虑users_controlleredit 操作。表单的所有必需的user 和关联的posts 属性将由formtastic 表单预填充

代码:

<%= semantic_form_for @user do |f| %>

  <%= f.input :name %>

  <%= f.inputs :posts do |p| %>
    <%= p.input :title %>
    <%= p.input :comment %>
  <% end %>

<% end %>

例如,我有一个 @user 和两个 posts 关联。 在做@user.posts的时候,结果是这样的。

 [
  [0] #<Post:0x0000000aa53a20> {
                   :id => 3,               
                :title => 'Hello World',
              :comment => 'Long text comes here'
  },
  [1] #<Post:0x0000000aa53a41> {
                   :id => 5,               
                :title => 'Hello World 2',
              :comment => 'Long text comes here too'
  }
] 

因此表单将包含两个要编辑的帖子字段。

实际上,我想要在这两个帖子之前再添加一个空白表单。

这可以通过在第 0 位的 @object.posts 结果中插入一个新的空 post 对象来轻松实现。

所以,我想要的 @object.posts 结果应该看起来像,

    [
      [0] #<Post:0x0000000aa53a50> {
                       :id => nil,               
                    :title => nil,
                  :comment => nil
      },
      [1] #<Post:0x0000000aa53a20> {
                       :id => 3,               
                    :title => 'Hello World',
                  :comment => 'Long text comes here'
      },
      [2] #<Post:0x0000000aa53a41> {
                       :id => 5,               
                    :title => 'Hello World 2',
                  :comment => 'Long text comes here too'
      }
    ] 

@user.posts获取此结构的任何解决方案?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 formtastic


    【解决方案1】:

    #edit 操作中执行如下操作:

    def edit
      #... your code
      @user.posts << Post.new
    end
    

    【讨论】:

    • 谢谢,我找到了其他方法,在执行 @user.posts.build@user.posts 时构建并向结果对象添加另一个新的空对象。是否有任何选项可以根据 id 对这些结果进行排序,而不使用 Post 模型中的默认范围?
    猜你喜欢
    • 2011-04-27
    • 2014-08-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2016-09-14
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多