简体   繁体   中英

Rails get data from child table in rails

I have three tables like

  1. users
  2. companies
  3. posts

users structure

user_id | f_name | l_name |
---------------------------
  1     |   abc  |  xyz   |
---------------------------
#Model User
has_many :companies

companies

company_id  |  user_id |  company_name  |
-----------------------------------------
     1      |    1     |      otto      |
-----------------------------------------
#Model Company
belongs_to :user
has_many :posts, :foreign_key => :company_id

posts

post_id  |  company_id  |  post_title  |
----------------------------------------
   1     |      1       |    helo mart |
----------------------------------------
#Model Post
belongs_to :company

I need view post from posts table which is created by user having user_id 1 and whose company_id is 1.

I don't know how much did it mean, because I'm newbie on ruby on rails.

考虑到您已经获取了该用户的公司ID,查询的问题将如下所示:

@posts = User.find(1).companies.find(1).posts

假设公司ID是唯一的(而不是每个用户唯一),则根本不需要查找用户。

posts = Company.find(1).posts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM