我是 ruby on rails 的新手,问题是:
我试图在有关汽车信息的循环中获取客户名称。汽车数据包含一个名为“belongs_to”的列,它是客户的 ID。
重要的一行:<td><%= @client.find(car.belongs_to) %></td>
Controller :
def index
@cars = Car.all
@client = Client.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @cars }
end
end
你们会怎么做?
最佳答案
您将使用模型来实现此目的:
class Car < ActiveRecord::Base
belongs_to :client
end
class Client < ActiveRecord::Base
has_many :cars
end
在您的 View 中:
@car.client
编辑
或者反过来:
@client.cars
# to iterate over them:
@client.cars.each do |car|
# do something with car
end
关于ruby-on-rails - 如何通过find方法调用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4808598/