1
votes

For suppose I have three database table eg:

users:

------------------------------------
user_id | name | email       |
------------------------------------
  1     | xyz  | [email protected] |
------------------------------------

companies:

------------------------------------
company_id | user_id | c_name |
------------------------------------
1          | 1       | abc    |
------------------------------------

posts:

------------------------------------
post_id | company_id | post_title |
------------------------------------
1       | 1          | etc        |
------------------------------------

This is my database.

Now I need at first I signup then create 1 or 2 or 3 companies into one user_id then create post into company_id.

Now create company under user also create post but not update company_id in post table below my code:

user model:

  has_many :companies

company model:

has_many :posts, :foreign_key => :company_id
belongs_to :user

post model:

belongs_to :user
belongs_to :company

How can I reach this solution?

Thanks

1
It is still unclear to me what you are trying to achieve... On a sidenote: thanks for formatting the code this well ;) - davegson
You'll be better implementing something and seeing if it works - Richard Peck
hi @thechamp, suppose for clearly understand I have created 3 companies which is company_id 1, 2 & 3, when I create post select company_id 2 then not update company_id 2 or anything in posts table, hope will clear - user5801103

1 Answers

0
votes

First, unless you have specific reasons not to use rails conventions, the primary keys in your tables should be called id, and not post_id, company_id, etc. This will happen automatically if you generate your models using rails generators (e.g. rails g model user name email, rails g model company c_name user:references, etc.)

Second, if I understand what you want to achieve, you should simply do:

User model

class User < ActiveRecord::Base
  has_many :companies
  # Rest of your code
end

Company model

class Company < ActiveRecord::Base
  has_many :posts
  belongs_to :user
  # Rest of your code
end

Post model

class Post < ActiveRecord::Base
  belongs_to :company
  # Rest of your code
end

If you follow the standards, you don't need to specify any :foreign_key, which anyway was wrong in your code.