has_many_and_belongs_to self-join association and conditional has_many - ruby-on-rails-3

We have these 3 models:
class Group < ActiveRecord::Base
attr_accessible :name
has_many :users
has_and_belongs_to_many :suppliers,
:class_name => "Group",
:foreign_key => "customer_id",
:association_foreign_id => "supplier_id"
has_and_belongs_to_many :customers,
:class_name => "Group",
:foreign_key => "supplier_id",
:association_foreign_id => "customer_id"
has_many :orders, :as => :orderable
validates :name => :presence => true
end
class User < ActiveRecord::Base
attr_accessible :email, :name
has_many :orders, :as => :orderable
belongs_to :group
validates :email, :name, :group_id, :presence => true
end
class Order < ActiveRecord::Base
belongs_to :orderable, :polymorphic => true
validates :orderable_id, :presence => true
end
According to the self-joined Group model we have 2 "types" of groups: customers and suppliers.
Now we want that the has_many :orders, :as => :orderable association should exist only for the customer group type and not for suppliers.
So, only a customer could have many orders while a supplier cannot have any Order associated.
Is there a way to achieve this? Or I have to split the Group model into Customer and Supplier models?
Thanks!

Related

ActiveRecord::HasManyThroughNestedAssociationsAreReadonly Error in Rails Admin

I just upgraded to Rails 3.2.10 and am getting an error message that I never used to get when updating a record via RailsAdmin.
ActiveRecord::HasManyThroughNestedAssociationsAreReadonly at /admin/vendor/12/edit
Message Cannot modify association 'Vendor#categories' because it goes through more than one other association.
This is my Vendor model:
class Vendor < ActiveRecord::Base
attr_accessible :name, :description, :banner_image, :logo_image, :intro_text, :thumb_image, :category_ids, :product_ids, :user_id, :remove_banner_image, :banner_image_cache, :remove_logo_image, :logo_image_cache
mount_uploader :banner_image, ImageUploader
mount_uploader :logo_image, ImageUploader
mount_uploader :thumb_image, ImageUploader
has_many :products, :dependent => :destroy
has_many :categories, :through => :products
belongs_to :owner, :class_name => "User",
:foreign_key => "user_id"
end
This is my Category model:
class Category < ActiveRecord::Base
attr_accessible :name, :product_ids, :category_ids
has_many :category_products do
def with_products
includes(:product)
end
end
has_many :products, :through => :category_products
end
This is my Product model:
class Product < ActiveRecord::Base
attr_accessible :name, :description, :price, :vendor_id, :image, :category_ids, :sku, :remove_image, :image_cache
mount_uploader :image, ImageUploader
belongs_to :vendor
has_many :category_products do
def with_categories
includes(:category)
end
end
has_many :categories, :through => :category_products
end
This is my CategoryProduct model:
class CategoryProduct < ActiveRecord::Base
attr_accessible :product_id, :category_id, :purchases_count
belongs_to :product
belongs_to :category
validates_uniqueness_of :product_id, :scope => :category_id
end
This happens because your association is nested, meaning (from rails source) :
A through association is nested if there would be more than one join table... which is your case here.
Apparently a workaround (I didn't test) is telling Vendor it doesn’t need to autosave the association.
has_many :categories, :through => :products, :autosave => false
You can mark the association as readonly and rails_admin will then not generate the category fields in the form for vendor:
has_many :categories, -> { readonly }, through: :products

Active admin has_many through delete association

I'm currently making association like this :
show do
h3 project.title
panel "Utilisateurs" do
table_for project.roles do
column "Prenom" do |role|
role.user.firstname
end
column "Nom" do |role|
role.user.lastname
end
column "email" do |role|
role.user.email
end
column "Role" do |role|
role.role_name.name
end
end
end
end
# override default form
form do |f|
f.inputs "Details" do # Project's fields
f.input :title
f.input :code
end
f.has_many :roles do |app_f|
app_f.inputs do
# if object has id we can destroy it
if app_f.object.id
app_f.input :_destroy, :as => :boolean, :label => "Supprimer l'utilisateur du projet"
end
app_f.input :user, :include_blank => false, :label_method => :to_label
app_f.input :role_name, :include_blank => false
end
end
f.buttons
end
I have the following associations :
Project
has_many :roles, :dependent => :destroy
has_many :users, :through => :role
User
has_many :roles, :dependent => :destroy
has_many :projects, :through => :role
Role
belongs_to :user
belongs_to :project
belongs_to :role_name
RoleName
has_many :roles
When I try to destroy user association through my form nothing happen, any idea to solve this ?
Or to add delete link to my show block ?
Try to add accepts_nested_attributes_for to your Project model (and roles_attributes to attr_accessible):
class Project < ActiveRecord::Base
has_many :roles, :dependent => :destroy
has_many :users, :through => :role
accepts_nested_attributes_for :roles, :allow_destroy => true
attr_accessible :roles_attributes, (+ all you had here before)
...
end
allow_destroy: true is the root of this issue.

RSpec testing non validating has_many through relationship

I have a many to many relationship between documents.
Say I have document1 and document2. I have a many to many table where there are parents and children.
document.rb
has_many :child_relationships, :class_name => "DocumentRelationship", :foreign_key => "child_id", :dependent => :destroy
has_many :parents, :through => :child_relationships, :source => :parent
has_many :parent_relationships, :class_name => "DocumentRelationship", :foreign_key => "parent_id", :dependent => :destroy
has_many :children, :through => :parent_relationships, :source => :child
document_relationship.rb
belongs_to :parent, :class_name => "Document", :foreign_key => "parent_id"
belongs_to :child, :class_name => "Document", :foreign_key => "child_id"
validates_uniqueness_of :child_id, :scope => [:parent_id]
validates_presence_of :parent_id
validates_presence_of :child_id
validate :obeys_chronology
def obeys_chronology
errors.add(:child_id, "must be created after its parent") if child_id.to_i < parent_id.to_i
errors.add(:child_id, "cannot be its own parent") if child_id.to_i == parent_id.to_i
end
If I say document2.children << document1 it appropriately fails validation, but I don't know how to write a test for this.
Is there a better way to do this?
Add it to the collection
document2.children << document1
document2.children.contain?(document1).should == false
Then make sure it's not in there.

How do I delete a record from all tables it is referred to?

Good morning fellow Overflowers,
Small problem with model associations. I have these model associations:
class Categorization < ActiveRecord::Base
belongs_to :exhibit
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :categorizations
has_many :exhibits, :through => :categorizations
acts_as_indexed :fields => [:title]
validates :title, :presence => true, :uniqueness => true
end
class Exhibit < ActiveRecord::Base
has_many :categorizations
has_many :categories, :through => :categorizations, :source => :category
acts_as_indexed :fields => [:title, :bulb]
validates :title, :presence => true, :uniqueness => true
belongs_to :foto, :class_name => 'Image'
end
So, essentially Categorization ends up with these columns (date/time stamps omitted):
categorization_id, exhibit_id and category_id.
My problem is that when I delete an Exhibit, its reference on the Categorization table is not deleted thus getting a DB error on my view. I have to first unassign the Exhibit from any Category and then delete it safely. Or (given for example that the Exhibit I delete has :exhibit_id=>'1') when I give in the rails console: Categorization.find_by_exhibit_id(1).destroy
Thanks for any help!!
You can set the :dependent options on associations that you want Rails to follow when you delete their parents:
class Exhibit < ActiveRecord::Base
has_many :categorizations, :dependent => :destroy
...
end

Rails has_many find associated items

So, got 2 models:
class Match < ActiveRecord::Base
has_many :rounds
has_many :participations
has_many :players, :through => :participations
belongs_to :clan_1, :class_name => "Clan", :foreign_key => "clan_1_id"
belongs_to :clan_2, :class_name => "Clan", :foreign_key => "clan_2_id"
belongs_to :winner, :class_name => "Clan", :foreign_key => "winner_id"
belongs_to :league
belongs_to :tournament
validates :clan_1_id, :presence => true
validates :clan_2_id, :presence => true
scope :by_league, lambda { |league| where("league_id == ?",league.id) }
scope :by_tournament, lambda { |tournament| where("tournament_id == ?",tournament.id) }
scope :played, where("played is not NULL")
scope :not_played, where("played is NULL")
end
class Clan < ActiveRecord::Base
has_many :players
has_many :rounds_won, :class_name => "Round", :foreign_key => "winner_id"
has_many :rounds_blue, :class_name => "Round", :foreign_key => "clan_blue_id"
has_many :rounds_purple, :class_name => "Round", :foreign_key => "clan_purple_id"
has_many :matches_won, :class_name => "Match", :foreign_key => "winner_id"
has_and_belongs_to_many :leagues
has_and_belongs_to_many :tournaments
def matches
Match.where("clan_1_id = ? OR clan_2_id = ?",self.id, self.id)
end
def matches_lost
matches.where("winner_id != ?", self.id)
end
def matches_drawn
matches.played.where("winner_id is NULL")
end
end
and I want to fetch all clans, which taken part in match.
You're over thinking it. Rails makes it very easy for you to do this.
class Comment < ActiveRecord::Base
belongs_to :post
end
class Post < ActiveRecord::Base
has_many :comments
end
#post.comments
If you have a column in your comment table with "modelName"_id (eg post_id) rails with automatically hook up the foreign key.
All you have to do is call #model1.model2 assuming #model1 is an instance of the model1 object.
If you want to hook up the query yourself you could use the where() method.
#comments = Comment.where(:post_id => some_id)
If you alter your associations a little bit you can utilize includes() in scopes:
class Match < ActiveRecord::Base
belongs_to :clan_1, :class_name => "Clan"
belongs_to :clan_2, :class_name => "Clan"
end
class Clan < ActiveRecord::Base
has_many :one_matches, :class_name => 'Match', :foreign_key => :clan_1_id
has_many :two_matches, :class_name => 'Match', :foreign_key => :clan_2_id
end
Then you can add this scope:
class Clan < ActiveRecord::Base
scope :participated_in_match, includes(:one_matches, :two_matches).where("matches.id IS NOT NULL")
end
This isn't tested so please let me know if you get unexpected results.
Quite simply:
model_two_object = Model_2.first # For clarity only, change to suit your needs
model_two_object.models_1