从控制器轨道中的类中获取值

时间:2013-03-21 13:32:04

标签: ruby-on-rails database rails-activerecord

标题有误导性,但我不确定如何说出这个。我有一个方法

   def showlease
   @tenant = Tenant.find(params[:id])
   @lease = @tenant.lease


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

因此,你可以看到我必须表租户和租赁。有没有办法从@lease中提取值?我的租约表有一个名为property_id的值,我希望得到@ lease.property_id的内容。然后我想使用这个值来获取我的另一个名为properties的表中的相应记录。这基本上是我想要的伪

@Property = Property.where(_id = (@lease.property_id)

即使我可以从我的观点中做到这一点,如果那可能是

 <p> Firstname: <%= @tenant.name %></p>
 <p> LeaseStart: <%= @lease.lease_start %></p>
  <p> LeaseStart: <%= @property(@lease.property_id).address %></p>

编辑:

以下是我的模特

class Lease < ActiveRecord::Base
  attr_accessible :lease_end, :lease_start, :property_id, :tenant_id
  belongs_to :tenant
  belongs_to :property
end

class Property < ActiveRecord::Base
  attr_accessible :address_line_1, :city, :county, :image, :rent
  has_one :lease
end

class Tenant < ActiveRecord::Base
  attr_accessible :email, :name, :phone
  has_one :lease
end

1 个答案:

答案 0 :(得分:0)

只要您在模型中定义了关联,您不需要按ID查找,您只需要询问相关对象即可。

<%= @lease.property.address %>
相关问题