简体   繁体   English

无法从View Rails 3.2访问关联的模型方法

[英]cannot access associated model methods from view rails 3.2

Situation 情况

  • I have two models cables and status 我有两种型号的电缆和状态
  • Cables belongs to status, and status has many cables 电缆属于状态,状态有很多电缆
  • Anywhere that is returning a single record the following code works 任何返回单个记录的地方,以下代码均有效

     @cable.status.stat #where stat is one of the columns in status 
  • However since my index returns All cables, when I try to access them from view by doing the following 但是,由于我的索引返回所有电缆,因此当我尝试通过以下操作从视图访问它们时

     <% @cables.each do |cable| %> <td><%= cable.Cable_Hex %></td> <td><%= cable.status.stat %></td> </tr> <% end %> 

I get an error stating that .stat is not recognized. 我收到一条错误消息,指出无法识别.stat。 When I remove .stat and leave it as cable.status then I just see an address. 当我删除.stat并将其保留为cable.status时,我只会看到一个地址。

If I try to access the foreign_id then I can see it without a problem. 如果我尝试访问foreign_id,那么我可以看到它而没有问题。 Clearly then associated methods are not readily available in view. 显然,相关的方法并不容易获得。

How do I access associated model methods from a view? 如何从视图访问关联的模型方法?

--Edit-- Including both Models as requested -编辑-根据要求包括两个模型

Model for Cables 电缆型号

class Cable < ActiveRecord::Base
    belongs_to :user, :inverse_of => :cables
    belongs_to :status, :inverse_of => :cables
end

Model for Status 状态模型

class Status < ActiveRecord::Base
    has_many :cables, :inverse_of => :statuses  
end

May be wrong sql for association. 关联的SQL可能错误。

SQL - SQL-

Cable.where("cables.status_id IS NOT NULL")

To get Status record you can use join 要获取状态记录,您可以使用join

 Status.joins( :cables ).where("cables.status_id IS NOT NULL")

This will return all Status records that have an association with Cables. 这将返回与电缆关联的所有状态记录。

Then you can loop through it to get stat for each status. 然后,您可以遍历它以获取每个状态的stat

Cause of the problems were faulty test vectors. 问题的原因是测试向量错误。 They were not initialized properly and the error returned for this was that stat method was not found. 它们未正确初始化,因此返回的错误是未找到stat方法。 This made me think that there was something wrong with passing the method across to view however I have learnt that for this particular problem there are two sides to consider. 这使我认为将方法传递给别人看是有问题的,但是我了解到,对于这个特定问题,有两个方面需要考虑。 Information that is currently being used to render the page AND proper associations. 当前用于呈现页面和适当关联的信息。

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

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