简体   繁体   中英

Ancestry Gem 'undefined method' error

I am using the Ancestry Gem and I am getting an undefined method "arrange" for #<Array:0x007f8d58e58700> error with the following code:

<%= @shipmgr_carriers.arrange(:order => :name) %>

However, When I just output @shipmgr_carriers I get an array with ancestry:

[#<Shipmgr::Carrier id: 9, name: "testing", status: nil, created_at: "2012-01-16 22:44:28", updated_at: "2012-01-16 22:44:28", ancestry: nil>, #<Shipmgr::Carrier id: 10, name: "test", status: nil, created_at: "2012-01-16 22:44:28", updated_at: "2012-01-16 22:44:28", ancestry: "9">] 

Can anyone tell me why I am unable to call the .arrange method on the array variable?

I haven't used Ancestry but it looks like it adds the arrange method to ActiveRecord::Base. It doesn't add this method to Array and so you shouldn't expect it to work on an array.

I'm assuming you're declaring @shipmgr_carriers in your controller something like this:

class SomeController < ActionController::Base
  def some_action
    @shimgr_carriers = SomeModel.find(...).carriers
  end
end

Try this instead:

def some_action
  @shipmgr_carriers = SomeModel.find(...).carriers

  @shipmgr_carriers_arranged = @shipmgr_carriers.arrange(...)
end

My hunch is that by the time @shipmgr_carriers gets to your view the query has already been run, transforming it into an array of results instead of a relation.

This is logic that should probably be done in the controller anyway, so moving it out of the view is a good idea regardless.

The arrange() method acts either at the class level or on a named scope, not on a returned array of values. For example, if you want to call arrange() on a table called 'Activity', this would work and return the entire table in an arranged format:

Activity.arrange

However, if you want to call arrange on a specific tree in the table you would go:

Activity.find(...).subtree.arrange

'subtree' is a named scope provided by the has_ancestry gem. Therefore, the arrange() method should work for the following named scope:

  • ancestors
  • children
  • sibblings
  • descendants
  • subtree

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM