2011-01-26 57 views
1

我是新來的紅寶石在軌道上,這裏是問題:如何通過查找方法調用變量

我想獲取有關汽車信息循環內的客戶端名稱。汽車數據包含一個名爲「belongs_to」的列,它是客戶的ID。

的重要線路:<td><%= @client.find(car.belongs_to) %></td>

控制器:

def index 
    @cars = Car.all 

    @client = Client.all 

    respond_to do |format| 
     format.html # index.html.erb 
     format.xml { render :xml => @cars } 
    end 
    end 

會如何你們這樣做嗎?

回答

7

你會使用模型來實現這一目標:

class Car < ActiveRecord::Base 
    belongs_to :client 
end 

class Client < ActiveRecord::Base 
    has_many :cars 
end 

並在您的視圖中:

@car.client 

編輯

或其他方式輪:

@client.cars 
# to iterate over them: 
@client.cars.each do |car| 
    # do something with car 
end 
+0

非常漂亮看一看非常感謝你! – criticerz 2011-01-26 20:25:33

2

嘗試

Client.find(car.belongs_to) 

你真正想要做什麼,雖然是有你的Car模型有這樣的事情

belongs_to :client 

而且你Client模型有

has_many :cars 

然後你可以簡單地撥打@car.client來獲得你的w螞蟻。

0

我想就像你可以這樣做:

@cars.each do |car| 
    car.client 
end 

和車型,我想你alredy有:

belongs_to :client 
4

belongs_to的是不是一個很好的列名。有一個稱爲「belongs_to的」在那裏你可以建立模型之間的關係,他們中的其中一個「belongs_to的」另一個模型關聯類型,如:

class Car < ActiveRecord::Base 
    belongs_to :client # there is a column on the cars table called "client_id" 
end 

class Client < ActiveRecord::Base 
    has_many :cars 
end 

然後,你可以做:

client = car.client 

Ruby on Rails Guides - A Guide to Active Record Associations