Ruby on rails 4 尝试订购时,上的SyntaxError与块有许多关联

Ruby on rails 4 尝试订购时,上的SyntaxError与块有许多关联,ruby-on-rails-4,has-many,Ruby On Rails 4,Has Many,在RubyonRails4中,假设父母有很多孩子。然后我想,并遵循链接的公认答案。这很有效: class Parent < ActiveRecord::Base has_many :children, dependent: :destroy do def persisted collect { |a| a if a.persisted? } end end 但这带来了一个错误: ParentsController索引中的SyntaxError …tru

在RubyonRails4中,假设父母有很多孩子。然后我想,并遵循链接的公认答案。这很有效:

class Parent < ActiveRecord::Base
  has_many :children, dependent: :destroy do
    def persisted
      collect { |a| a if a.persisted? }
    end
  end
但这带来了一个错误:

ParentsController索引中的SyntaxError

…trunk/app/models/parent.rb:3:语法错误,意外的关键字\u do\u块,预期=>…trunk/app/models/parent.rb:49:语法错误,意外的关键字\u end,预期输入结束

但是,这确实有效:

has_many :children, -> { order 'id asc' } do
has_many :children, -> { order 'id asc' }, { dependent: :destroy } do
  def persisted
    collect { |a| a if a.persisted? }
  end
end

我甚至找不到关于如何在关联上使用do_块的文档。感谢您的帮助。

我的方法有两个问题:

  • 参数的顺序。在rails 4中,范围在选项之前
  • 选项散列应该被包装,因为它不再是最后一个参数
  • 因此,此代码确实有效:

    has_many :children, -> { order 'id asc' } do
    
    has_many :children, -> { order 'id asc' }, { dependent: :destroy } do
      def persisted
        collect { |a| a if a.persisted? }
      end
    end
    
    参考资料:


    我的方法有两个问题:

  • 参数的顺序。在rails 4中,范围在选项之前
  • 选项散列应该被包装,因为它不再是最后一个参数
  • 因此,此代码确实有效:

    has_many :children, -> { order 'id asc' } do
    
    has_many :children, -> { order 'id asc' }, { dependent: :destroy } do
      def persisted
        collect { |a| a if a.persisted? }
      end
    end
    
    参考资料:


    我的方法有两个问题:

  • 参数的顺序。在rails 4中,范围在选项之前
  • 选项散列应该被包装,因为它不再是最后一个参数
  • 因此,此代码确实有效:

    has_many :children, -> { order 'id asc' } do
    
    has_many :children, -> { order 'id asc' }, { dependent: :destroy } do
      def persisted
        collect { |a| a if a.persisted? }
      end
    end
    
    参考资料:


    我的方法有两个问题:

  • 参数的顺序。在rails 4中,范围在选项之前
  • 选项散列应该被包装,因为它不再是最后一个参数
  • 因此,此代码确实有效:

    has_many :children, -> { order 'id asc' } do
    
    has_many :children, -> { order 'id asc' }, { dependent: :destroy } do
      def persisted
        collect { |a| a if a.persisted? }
      end
    end
    
    参考资料: