vendredi 12 février 2016

Rails 3 has_many :through association, change order in "join" table, based on custom ordering in cms

I am working on a feature in a rails 3 app. I have dabbled in a few programming languages, but so far worked mainly with ruby and rails. So I am not a proficient programmer and please bare with me if I am not clear enough.

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:

    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

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

[1] pry(main)> b = Box.first
Box Load (2.0ms)  SELECT "boxes".* FROM "boxes" LIMIT 1
=> #<Box id: 1, name: "Test", image: nil, ....                        
[2] pry(main)> b.products
Product Load (1.6ms)  SELECT "products".* FROM "products" INNER JOIN
"box_products" ON "products"."id" = "box_products"."product_id"
WHERE "box_products"."box_id" = 1
=> []
[3] pry(main)> b = Box.where("id" => 2)
Box Load (0.8ms)  SELECT "boxes".* FROM "boxes" WHERE   
"boxes"."id" = 2
=> [#<Box id: 2, name: "Yoo", image: "image.jpeg" ....
[4] pry(main)> b.products
NoMethodError: undefined method `products' for # 
<ActiveRecord::Relation:0x007f3b68c30208>
from /home/vagrant/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/activerecord-3.2.13/lib/active_record/relation/delegation.rb:45:in `method_missing'

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.

Another thing that I am trying to implement, is that when I see a table of products on the Box page, I can drag them around, to change the order of products, based on my liking. To save this, I have an ajax query that posts to "sort_box_products_path", and therefore a sort method in BoxProductsController. I am confused with how to implement this. If a box has 3 products that have id 5, 7, 9 respectively in the BoxProduct table, and I want to change those ids to 7, 5, 9 respectively, so it appears in my CMS and json in a specific custom order, how do I implement the sort method in the box controller. I would really appreciate guidance on this one.

Thank you

Aucun commentaire:

Enregistrer un commentaire