简体   繁体   English

从rails上的ruby中的另一个模型访问数据

[英]accessing the data from another model in ruby on rails

I have 2 models named Subject & Page. 我有2个名为Subject&Page的模型。 there is 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

I have list.html.erb in view -> pages folder. 我在view - > pages文件夹中有list.html.erb。

Q. My qus is I want to show all the subject_id in list.html.erb. 问:我的问题是我想在list.html.erb中显示所有subject_id。 how? 怎么样? for that which changes I have to do in pages_controller & list.html.erb so that I will got solution... 对于那些我必须在pages_controller和list.html.erb中做的更改,以便我得到解决方案......

You can access any Model in any Controller in following way 您可以通过以下方式访问任何Controller中的任何模型

   @instance_variable = ModelClass.all

In your case it should be something like following 在你的情况下,它应该像下面这样

pages_controller.rb pages_controller.rb

def list 
  @subjects_list = Subject.all
end

app/views/pages/list.html.erb 应用程序/视图/页/ list.html.erb

<% for subject in @subjects_list %>
  <!--  Your Code Here  -->
<% end %>

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

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