has_many :through association, &#34;No Method Error&#34; in rails console in shell, NoMethodError: undefined method for #<activerecord::relation:>

时间:2016-02-12 20:55:15

标签: ruby-on-rails ruby ruby-on-rails-3 postgresql sorting

I am working on a feature in a rails 3 app. I have a new model, called Box which has many "Product"(s). The has_and_belongs_to_many was giving me trouble. So I made a new model called BoxProduct. It looks like this:

Params = new List<XamlFriendlyKeyValuePair<string, string>>();
Params.Add{"Key1", "Value1"};
Params.Add{"Key1", "Value2"};

-The first issue I am running into here is: When I access a Box in the rails console:

    class Box < ActiveRecord::Base
    attr_accessible :name, :product_ids
    has_many :box_products, :class_name => 'BoxProduct'
    has_many :products, through: :box_products
    accepts_nested_attributes_for :box_products
    end


    class BoxProduct < ActiveRecord::Base
    attr_accessible :box, :product
    belongs_to :box
    belongs_to :product
    end

    class Product < ActiveRecord::Base
    include Concerns::Notifiable
    include ThinkingSphinx::Scopes

    attr_accessible :box_ids


    has_many :box_products
    has_many :boxes, through: :box_products
    end

However, in the CMS, in the box view page, @box.products returns the products for each box in a table as implement, for all Box entries that I have created so far.

1 个答案:

答案 0 :(得分:2)

您的第一个问题很容易解决:请注意,即使只找到一个条目,where也不会从数据库中返回一个对象。 where会返回ActiveRecord::Relation,在您的问题的上下文中充当列表。

Box.where("id" => 2)
#=> [#<Box id: 2, ... # Note the `[` at the beginning of the line

并且您无法在此products上致电Relation,因为products已在Box上定义,但未在Relation上定义。

您可以根据需要以不同方式解决此问题。

您可以遍历该列表并在每个条目上调用products

Box.where(id: 2).map(&:products)
Box.where(id: 2).includes(:products)

或者您可以使用仅返回单个元素的方法:

Box.find(2).products
Box.find_by(id: 2).products
Box.where(id: 2).take.products
Box.where(id: 2).first.products