How to Has_And_Belongs_To_Many Multiple Instances of the Same Model

How can I has_and_belongs_to_many multiple instances of the same model?

This is doable, but I strongly recommend using has_many :through instead:

class Node < ActiveRecord::Base
has_many :parent_node_links,
:class_name => 'NodeLink',
:foreign_key => :child_id

has_many :parents,
:through => :parent_node_links,
:source => :parent

has_many :child_node_links,
:class_name => 'NodeLink',
:foreign_key => :parent_id

has_many :children,
:through => :child_node_links,
:source => :child
end

class NodeLink < ActiveRecord::Base
belongs_to :parent,
:class_name => "Node"
belongs_to :child,
:class_name => "Node"
end

Having a first-class join model makes it much easier to manage the relationships and gives you the freedom to add relevant meta-data at a later point in time.

Has many AND HABTM on the same model

The first argument to habtm is the name of the method you'll call to get the collection. It can be anything you want, so long as you specify the model class with :class_name

has_and_belongs_to_many :supported_sites, :class_name => 'Site'

Depending on how you name things in your database, you might also need to specify :join_table, :foreign_key, or :association_foreign_key. Take a look at the Options section of http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many for more info.

multiple habtm relationships on one model

The HABTM relationship in Rails has seemed to fall out of favor over the last couple of years with Rails developers to the has_many :through relationship. The only time you should use HABTM is when you have no need for any additional information about the relationship between two models. In your case, you are trying to emulate this by creating two HABTM relationships when you could effectively accomplish by having a join model with a editable attribute.

In code, it would look something like this:

class Page < ActiveRecord::Base
has_many :page_permissions
has_many :user_types, :through => page_permissions

def editable_user_types
page_permissions.includes(:user_types).where(:editable => true).map(&:user_type)
end

def read_only_user_types
page_permissions.includes(:user_types).where(:editable => false).map(&:user_type)
end
end

class PagePermission < ActiveRecord::Base
belongs_to :page
belongs_to :user_type
# When you create this model, you should have a boolean attribute for editable
end

class UserType < ActiveRecord::Base
has_many :page_permissions
has_many :pages, :through => :page_permissions
end

I think following this approach will allow you to consolidate to one join table which will be better in the future if you need to add additional attributes to the relationship (PagePermission) between Page and UserType.

habtm multiple times with the same model

It means that if class Publication is linked to a table with no standard name, example "my_publications":

class Publication < ActiveRecord::Base
set_table_name "my_publication"
end

The set table name should be put behind the habtm declaration for this to work:

class Publication < ActiveRecord::Base
has_and_belongs_to_many :authors, :class_name=>'Person'
has_and_belongs_to_many :editors, :class_name=>'Person'
set_table_name "my_publication"
end

Rails: How to setup multiple relation types to same models

You can simply do it like this i guess

class Product < ApplicationRecord
has_and_belongs_to_many :categories
belongs_to :main_category, class_name: 'Category', foreign_key: :main_category_id
end
class Category < ApplicationRecord
has_and_belongs_to_many :categories
has_many :main_products, class_name: 'Product', foreign_key: :main_category_id
end

You will have to add an column to products table called main_category_id

Source https://guides.rubyonrails.org/association_basics.html#bi-directional-associations

cakephp HABTM same model

Your relation is fine. What you have written will create a Product Model that can have any number of Ingredients and allows an Ingredient to belong to any number of Products.

When saving, you must simply treat the Ingredient as if it were another Model. The CakePHP example on saving HABTM works just as well as for associating the same model as with 2 different models: http://book.cakephp.org/2.0/en/models/saving-your-data.html.

So, if you're saving multiple Ingredients to a Product, your Array structure will look like this:

Array(

    [0] => Array(

        Product => Array(

            id => 1

        ),

        Ingredient => Array(

            id => 18

        )

        ),

    1 => Array(

        Product => Array(

            id => 1

        ),

        Ingredient => Array(

            id => 23

        )

    )

    // ...

    )

It is up to you how you capture this in a form, but the form example used in the link provided above should manage this properly.

CakePHP multiple model conditions in find() with HABTM

You're looking for the Containable behavior; e.g.

// app_model.php
var $actsAs = array(
'Containable'
);

I'm assuming User extends AppModel, so Containable will be set for the child (User). Now, in your controller, conditions for the related class can be placed in the 'contain' key of the second argv of find(); e.g.

// users_controller.php
$this->User->find('first', array(
'conditions' => array('User.id' => $userId),
'contain' => array(
'Item' => array(
'conditions' => array('Item.symbol' => $itemSymbol)
)
)
);

Cake will find the matching User and retrieve matching Items (with the same user_id and the Item.Symbol specified. But be very careful to use 'contain' => array() when it is not required, otherwise Cake will retrieve all of the defined associations, which will tax your database.



Related Topics



Leave a reply



Submit