The model name (Contact) same as anther model(user) column name (contact) same
example:
User.first
#<User id: 2, username: "xyz", created_at: "2020-08-21 12:36:10", updated_at: "2021-12-04 16:10:29", email: "xyz#gmail.com", is_active: true, job_title: nil, defualt_role: "Super Admin", **contact**: "9900855603">
Contact.first
=> nil
I need to find out user contact
query is:
User.first.contact
showing nil
=> nil
please help on this.
Either you define a 1:N relation between user and contact (User has many Contacts) or differentiate the model reference name
1:N solution
on user.rb
has_many :contacts
1:1 solution
on user.rb
has_one :user_contact, foreign_key: :user_id, class_name: :Contact
Related
I'm inheriting a codebase for a Rails app that uses a blog engine -- and I am not making sense of how the models interact.
What I want to do is show the author who is associated with a specific article.
There is a table for articles called LinesArticle. An example entry:
<LinesArticle id: 2, title: "Example Article", sub_title: "Example Title",
content: "Example Content", published: true, published_at: "2017-08-22 00:00:00",
created_at: "2017-08-23 06:15:33", updated_at: "2017-08-23 06:15:36", slug: "whatever",
featured: false, document: nil, short_hero_image: "", teaser: "">
Next, there is a table for Authors called LinesAuthor. An example entry that should be associated:
#<LinesAuthor id: 1, name: "John Doe", email: "jd#examplesitedotcom", created_at: "2017-08-19 07:46:04", updated_at: "2017-08-19 07:46:04">
So if I compare these two tables, there isn't a connection between the data that would make sense for the models. So then I found LinesAuthorable that I think connects them. An entry:
<LinesAuthorable id: 2, author_id: 1, article_id: 2,
created_at: "2017-08-23 06:15:33", updated_at: "2017-08-23 06:15:33">
So my thinking is, if my controller calls an article like #articles = LinesArticle.last and I want to show the author who wrote that article by matching article_id to the matching result in LinesAuthorable and then query LinesAuthor for the matching author_id.
Reading through the documentation, I have now created models where an Article model belongs_to :lines_authorable and Author has_many :Lines_Authorable. If that is the right approach, how would you call that in the view to actually show the Author?
The LinesAuthorable table is acting as a through table, you can use a has_many through relationship to connect the data, something like:
class LinesArticle < ApplicationRecord
has_many :lines_authorables, foreign_key: :article_id
has_many :lines_authors, through: :lines_authorables
end
class LinesAuthor < ApplicationRecord
has_many :lines_authorables, foreign_key: :author_id
has_many :lines_articles, through: :lines_authorables
end
class LinesAuthorable < ApplicationRecord
belongs_to :line_article, foreign_key: :article_id
belongs_to :line_author, foreign_key: :author_id
end
You can then access an article's authors, and likewise an author's articles directly through the relationship:
#article = LinesArticle.first
#article.lines_authors #=> #<LinesAuthor::ActiveRecord_Relation...>
#author = LinesAuthor.first
#author.lines_articles #=> #<LinesArticle::ActiveRecord_Relation...>
I created 3 models as below, and used cocoon nested form to create associations between them.
class Unit < ApplicationRecord
has_many :mapping_categories, -> { distinct }, dependent: :destroy, inverse_of: :unit
accepts_nested_attributes_for :mapping_categories,
allow_destroy: true,
reject_if: :all_blank
end
class MappingCategory < ApplicationRecord
belongs_to :unit
has_many :mapping_items, -> { distinct }, dependent: :destroy, inverse_of: :mapping_category
accepts_nested_attributes_for :mapping_items,
allow_destroy: true
end
class MappingItem < ApplicationRecord
belongs_to :mapping_category
has_many :mapping_item_links
has_many :linked_mapping_items, through: :mapping_item_links, dependent: :destroy
end
Each mapping_item can have many other mapping_items through a joint table. In every mapping_item section in Unit form, this association is displayed as a select input.
When creating or updating Unit, there are many mapping_categories tabs in the Unit form, and there are many mapping_items sections in each mapping_category section.
For example, I have Mapping Category A and Mapping Category B. I want to add Mapping Item 1 to Mapping Category A and Mapping Item 2 to Mapping Category B. The question is: How to create the association between Mapping Item 1 and Mapping Item 2, as these two items are not saved yet?
Thanks in advance.
YOU CAN DO IT
You have to write right code
user = User.new(name: 'Jons', email: 'jons#qq.ww')
bank_account = BankAccount.new(number: 'JJ123456', user: user)
bank_account.save
in this way will be saved both raws and user and bank_account
in your case:
unit = Unit.new(mapping_categories: [mapping_category])
mapping_category = MappingCategory.new(mapping_items: [mapping_item])
mapping_item = MappingItem.new
unit.save
and if you wanna use nested_attributes, you just have to build hash with attributes
params = { mapping_categories: [mapping_items: [{.....}]}] }
Unit.create(params)
but you have to figure out with right nesting
From my understanding of your question... You can't. These items don't yet have ids and there for can't be associated with another model.
> contact = Contact.new(full_name: "Steve", email:"example#asdf.com")
=> #<Contact id: nil, full_name: "Steve", email: "example#asdf.com", created_at: nil, updated_at: nil>
> invoice = Invoice.new(contact_id: contact.id, invoice_type: "Something")
=> #<Invoice id: nil, contact_id: nil, invoice_type: "Something" created_at: nil, updated_at: nil>
> invoice.save
=> false
The idea is that i have a table users and a table customers. Each user has many customers that are related only to them. Actually Im using this model. So every customer that will be created will also get the related user_id in the customers table.
class Customer
belongs_to :user
end
class User
has_many :customers
end
After some SO question it was stated to me that I should use this model, for the same result.
class Customer
has_one :user
end
class User
belongs_to :customer
end
But i dont get the difference. Any easy explaination wether Im right with my way or what is wrong.
regards
denym
It won't actually be the same result...
The first one:
class Customer
belongs_to :user
end
class User
has_many :customers
end
Will set a user_id in the Customer and nothing in the User. That means that a customer can only be related to one user. In terms of reflections you can do stuff like this:
user = User.create(name: 'John Snow')
customer = user.customers.build(name: 'Tywin Lannister')
customer.save
user.inspect
=> #<User id: 8, name: "John Snow">
customer.inspect
=> #<Customer id: 12, user_id: 8, name: "Tywin Lannister">
user.customers.inspect
=> [#<Customer id: 12, user_id: 8, name: "Tywin Lannister">]
customer.user
=> #<User id: 8, name: "John Snow">
The second one:
class Customer
has_one :user
end
class User
belongs_to :customer
end
Will set a customer_id in the user. You can do stuff like this:
customer = Customer.create(name: 'Tywin Lannister')
user = customer.build_user(name: 'John Snow')
user.inspect
=> #<User id: 8, customer_id: 12, name: "John Snow">
customer.inspect
=> #<Customer id: 12, name: "Tywin Lannister">
user.customer
=> #<Customer id: 12, name: "Tywin Lannister">
customer.user
=> #<User id: 8, customer_id: 12, name: "John Snow">
So in your case
Well you need the first one.
From the documentation:
A belongs_to association sets up a one-to-one connection with another model, such that each instance of the declaring model “belongs to” one instance of the other model.
A has_one association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model.
I've created two models with the below associations
class User < ActiveRecord::Base
has_many :roles, :dependent => :destroy
end
class Role < ActiveRecord::Base
belongs_to :user
end
class Student < Role
end
class Tutor < Role
end
However when I create a new child role, I assume it would get associated to the model it has the belongs to for.
Such as:
Tutor.create(:user_id => user_id)
I would expect:
#some user #user
#user.roles
to have an array containing a Tutor. However, it doesn't seem to be working. Any ideas what I'm doing wrong?
Once you start using Single Table Inheritance, than the Tutor that you created isn't a role, as far as active-record is concerned for this type of query.
class User < ActiveRecord::Base
has_many :roles
has_many :tutors
end
#user = User.first
#user.roles
=> []
#user.tutors
=> [#<Tutor id: 1, user_id: 1, type: "Tutor", created_at: "2012-10-26 18:15:16", updated_at: "2012-10-26 18:15:16">]
If you want to get a list of all roles that your users may have:
Role.where(user_id: #user.id).all
[#<Tutor id: 1, user_id: 1, type: "Tutor", created_at: "2012-10-26 18:15:16", updated_at: "2012-10-26 18:15:16">, #<Student id: 2, user_id: 1, type: "Student", created_at: "2012-10-26 18:18:32", updated_at: "2012-10-26 18:18:32">]
I'm new to rails and testing and have a problem with loading my fixtures.
payment.yml
payment:
name: something
amount: 1.5
event: some_event
user: some_user
description: long text
users: some_user, some_user2
users.yml
some_user:
email: test#test.com
nick: name
some_user2:
email: test#test.com
nick: name
okey, so the problem is that when I'm doing the functionaltest for creating a payment
test "should create payment" do
assert_difference('Payment.count') do
post :create, :payment => #payment.attributes
end
it just sends
< Payment id: nil, name: "something", amount: 1.5, event_id: 972288058, user_id: 63246679, created_at: "2010-11-05 19:56:53", updated_at: "2010-11-05 19:56:53", description: "long text" >
and not the users array with multiple users. I use the "user" to define who owns the payment and users (in a seperate join table) as a list of users sharing the payment.
Any idea what I'm doing wrong?
here is the model for payments
class Payment < ActiveRecord::Base
has_many :comments, :as => :commentable, :dependent => :destroy
belongs_to :event
belongs_to :user
has_and_belongs_to_many :users
end
Can you put the model for payment? I had something similar and the problem was that the model was different. For example, if it's a ActiveRecord class, you have to check how it and its relationships. For example, if the event is actually an "event_id" that belongs_to an "event" class, then you should put something similar to this:
payment.yml
payment:
name: something
amount: 1.5
event_id: 1
user_id: 1
...
user.yml
id: 1
name: David Smith
status: Branch Manager
...
event.yml
id: 1
name: overdraft charge