简体   繁体   English

Ruby on Rails模型/控制器访问

[英]Ruby on Rails model/controller access

I have two models, subject and page . 我有两个模型, subjectpage I created a one-to-many association between them. 我在它们之间建立了一对多关联。

class Subject < ActiveRecord::Base
  has_many :pages
  attr_accessible :name
  attr_accessible :position
  attr_accessible :visible
  attr_accessible :created_at
end

and

class Page < ActiveRecord::Base
  belongs_to :subject

  attr_accessible :subject_id
  attr_accessible :name
  attr_accessible :permalink
  attr_accessible :position
  attr_accessible :visible
  attr_accessible :created_at
end

As mentioned above, I have two models, and I want to access all subject names which are in the Subject model to the page model/controller... 如上所述,我有两个模型,我想将主题模型中的所有主题名称访问到页面模型/控制器...

试试看:

Subject.select("subjects.name").joins(:pages).uniq

Below is how you can access subject's pages or page's subject. 以下是访问主题页面或页面主题的方式。

s = Subject.create(<params>)
s.pages  # array of page objects

p = Page.create(<params>)
p.subject # subject object

If you want to get all the subjects saved in a subject model use: 如果要获取保存在主题模型中的所有主题,请使用:

Subject.pluck(:name)

or to access a subjects associated with particular page: 或访问与特定页面相关的主题:

page = Page.first
page.subject  #subject object associated with the page

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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