I have created two models 1) Contact 2) Customer in my Rails application, now I want to join the two tables of these models. Tables are contacts & customers respectively. I am using following code:
1) contact.rb:
class Contact < ActiveRecord::Base
unloadable
has_many :customers
end
2) customer.rb
class Customer < ActiveRecord::Base
belongs_to :contact, :foreign_key => :contact_id`
end
3) customers_controller.rb
def new
#customer = Customer.new
#customer = Customer.find(:all,:include => :contact_id)
end
Here I am trying to access the primary key of contact table into customer table but it repeatedly gives this error "Association named 'contact_id' was not found; perhaps you misspelled it?" Can any one help me on this?
When you use include, you should pass in the association name (in your case "contact") rather than the foreign key.
However, your description doesn't make clear that this is what you want to do, so if you can clarify your question I'll update this answer if it's wrong
If I clearly understand you don't need to pluralize customer in the contact model :
class Contact < ActiveRecord::Base
unloadable
has_many :customers
end
And you don't need to specified the name of the column who contain the foreign key
(sorry for my english)
Related
In my Ruby on Rails app, i've created a join table in my database to link customers and businesses. Now i'm trying to find information on one of the models based on the information in the join table (called "conflicts"):
#customer = Customer.where(customer_id: 1).conflict(s) Or
#customer = Customer.find(1).conflict(s)
I want to find information about the customer (or business) directly tied to a given "conflict", and print that to the browser view.
Error i'm getting now:
undefined method `conflicts' for #
To get conflict through customer you should have following association in Customer model(customer.rb),
has_one :conflict
OR
has_many :conflicts
As per the description provided you have created a join table having the reference of both customers and businesses.
And the error you have provided, it seems like you forgot to associate them in your models.
customer.rb
class Customer < ApplicationRecord
has_many :customer_conflicts
has_many: conflicts, through: :customer_conflicts
end
conflict.rb
class Conflict < ApplicationRecord
has_many :customer_conflicts
has_many :customers, through: :customer_conflicts
end
customer_conflict.rb
class CustomerConflict < ApplicationRecord
belongs_to :customer
belongs_to :conflict
end
Now running the below mentioned queries will work:
#customer = Customer.where(customer_id: 1).conflicts
#customer = Customer.find(1).conflicts
i have two tables
1)Properties :fields are id, name, propert_type,category_id
2)Admins : fields id, name,mobile,category_id
i want to write an active record to list all properties , where category_id in properties table and category_id in Admins table are equal, according to current_user_id
i am listing this property list by logging as admin.
model relation
class Category < ActiveRecord::Base
has_many :admins,dependent: :destroy
has_many :properties,dependent: :destroy
end
class Admin < ActiveRecord::Base
belongs_to :category
has_many :properties
end
class Property < ActiveRecord::Base
belongs_to :admin
belongs_to :category
end
i wrote active record like this , but i got error,
can anyone please suggest me a solution for this
#properties= Property.where('properties.category_id=?','admins.category_id=?').and('admins.id=?',current_user.specific.id)
With your assosciation,You can use a sub query for getting your result in one line
#properties = Property.where(category_id: Admin.select("category_id").where(id: current_user.id))
As per my understanding current_user is an Admin. So You can search by the category_id of current_user. If I'm right, try this
#properties = Property.where(category_id: current_user.category_id)
I am using concerns for my rails application. I've different kind of users so I have made a loggable.rb concern.
In my concern I have
included do
has_one :auth_info
end
because every of my user that will include the concern will have an association with auth_info table.
The problem is, what foreign keys I need to put in my auth_info table?
E.G
I've 3 kind of users:
customer
seller
visitor
If I had only customer, in my table scheme I would have put the field
id_customer
but in my case?
You can solve this with polymorphic associations (and drop the concern):
class AuthInfo < ActiveRecord::Base
belongs_to :loggable, polymorphic: true
end
class Customer < ActiveRecord::Base
has_one :auth_info, as: :loggable
end
class Seller < ActiveRecord::Base
has_one :auth_info, as: :loggable
end
class Visitor < ActiveRecord::Base
has_one :auth_info, as: :loggable
end
Now you can retrieve:
customer.auth_info # The related AuthInfo object
AuthInfo.first.loggable # Returns a Customer, Seller or Visitor
You can use rails g model AuthInfo loggable:references{polymorphic} to create the model, or you can create the migration for the two columns by hand. See the documentation for more details.
Since user has roles 'customer', 'seller', 'visitor'.
Add a column called role to Users table.
Add a column called user_id to auth_infos table.
class AuthInfo < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_one :auth_info
end
you can do
user = User.first
user.auth_info
Now you a additional logic to your concerns.
I was trying to find answer on my question, but didn't success with it.
I have models Event, participants, participation_form, invitation, user.
Event has_many participants
User has_many invitations
User has_many participation_form
For Participant I want to have field like "based_on" and it will be references with invitation or participation_form.
I have one idea about it - make two fields and one model method that will be check which field contains value and return "based_on"
My question is - is there any way to reference one model to two models with pair of fields - class (model name) and value (id) so I will add another type if I need it in future.
You could use polymorphic associations for that: (http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
Could you tell more about models relations so I can write some example? Why do you need Participant model?
As mentioned byKuba Ploskonka, you'll probably benefit from a polymorphic association here:
--
Setup
For Participant I want to have field like "based_on" and it will be references with invitation or participation_form.
As per your specifications, you'll want to use the following:
#app/models/participation.rb
Class Participation < ActiveRecord::Base
belongs_to :participle, polymorphic: true
end
#app/models/invitation.rb
Class Invitation < ActiveRecord::Base
has_many :participations, as: :participle
end
#app/models/participation_form.rb
Class ParticipationForm < ActiveRecord::Base
has_many :participations, as: :participle
end
This will give you the ability to save your objects as follows:
#app/controllers/invitations_controller.rb
Class InvitationsController < ApplicationController
def create
#invitation = Invitation.new invitation_params
#invitation.participations.build #-> will save a blank "Participation" object
#inviation.save
end
end
I have the following:
class User < ActiveRecord::Base
has_one :subscription
end
class Subscription < ActiveRecord::Base
belongs_to :user
end
The User has a subscription_id and thus can have only one subscription (which is what I want).
Which works fine, but now I do:
#users = User.find(:all)
and I want all the subscriptions to be included.
I tried:
#users = User.find(:all, :include=>[:subscription]) # include subscription
But that would like the subscription table to have a user_id (SQLite3::SQLException: no such column: subscriptions.user_id: SELECT "subscriptions".* FROM "subscriptions" WHERE ("subscriptions".user_id = 2)).
Which is (ofcourse) not what I want.
I am new at RoR and I couldn't find a good example of this case in the books I have nor on the web.
I think you have your associations the wrong way round on the model objects. You should have
class User < ActiveRecord::Base
belongs_to :subscription
end
class Subscription < ActiveRecord::Base
has_one :user
end
belongs_to should be used on the side of the association that defines the foreign key (in this case subscription_id). Semantically this probably looks a bit odd, but that's because in this case rails would kind of expect a user_id to be on the subscriptions table instead of the other way round as you have it.
After that
User.find(:all, :include=>[:subscription])
Should work fine
First of all if the user has foreign key (subscription_id) then it should have belongs_to not the other way around. As the Rails docs says for has_one method:
"This method should only be used if the other class contains the foreign key. If the current class contains the foreign key, then you should use belongs_to instead"
(taken from: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001834)
Second, in your example you tried to find User and include user. You need to do this:
#users = User.find(:all, :include=>[:subscription])