2010-06-03 143 views
0

我无法访问我的轨道模型正确的信息(我认为是正确的),我的表的模式是Rails的关联查询

create_table :schools do |t| 
    t.string :name 
    t.timestamps 
end 

create_table :variables do |t| 
    t.string :name 
    t.string :category 
    t.timestamps 
end 

create_table :data do |t| 
    t.string :entry 
    t.decimal :rank, :scale => 3 
    t.integer :school_id, :null => false 
    t.integer :variable_id, :null => false 
    t.timestamps 
end 

模型类:

class Datum < ActiveRecord::Base 
    belongs_to :school 
    belongs_to :variable 
end 

class School < ActiveRecord::Base 
    has_many :data 
    has_many :variables, :through => :data 
end 

class Variable < ActiveRecord::Base 
    has_many :data 
    has_many :schools, :through => :data 
end 

这里是我的学校show.html.erb页面当前:

<h2> <%= @school.name %> </h2> 

<table> 
<% @school.variables.each do |variable| %> 
<tr><tr/> 
<td><%= variable.name %></td> 
<td><%= Datum.find(:first, :conditions => {:school_id => @school.id, :variable_id => variable.id}).entry %></td> 
<td><%= link_to 'Edit', edit_school_path(@school) %></td> 
<td><%= link_to 'Back', schools_path %></td> 
<% end %> 
</table> 

它做我想要它,但它确实很多很多queri ES。我假设我必须做急切的加载,但基于我在网上找到的例子,我无法弄清楚如何做到这一点(我真的是新的轨道)。有没有人有任何想法?

回答

2

试试这个,看看你是否得到你期望的结果,以及减少查询次数。

Datum.find(:first, 
      :conditions => {:school_id => @school.id, :variable_id => variable.id}, 
      :include => [:school, :variable]) 

此外,MVC原则规定您不应该在您的视图中查找;相反,在控制器的方法(应用程序/控制器/ school_controller.rb,方法Show)做

@data = Datum.find(....) 

,并在视图:

<%= @data.entry %> 

这样,你不污染与DB访问你的看法关注。

0

那么你正在做一个循环内的Datum.find查询。 Rails会这样做对于@ school.variables返回的每个元素

查找语句应该真的在控制器中完成。用一个或两个精心构建的发现,使用预先加载来设置您需要的变量。然后把HTML的东西,在你的每个循环到部分(名为类似“_variable”),并把它在你的观点是这样的:

<% render :partial 'variable', :collection => @school.variables %> 

里面你的名字命名的局部变量的部分部分来自其中的收集当前成员的数据。 Rails会照顾你的循环。

我希望有帮助。