【问题标题】:Relational database show fields from different tables in view, rails关系数据库在视图中显示来自不同表的字段,rails
【发布时间】:2013-05-23 13:10:04
【问题描述】:

我有 4 张桌子,customercustomer_sitesiteconnectioncustomersite 有很多 customer_sitessite 有很多 connections。这一切都在我的模型中设置好了。现在我试图为每个客户提供一个视图,显示与该客户相关的每个连接。这是我的看法:

 <% @connection.each do |l| %>
   <tr>
      <td><%= l.interface %></td>
      <td><%= l.device %></td>
      <td><%= l.speed %></td>
      <td><%= l.site.name %></td>
   </tr>
 <% end %>

这是我的控制器:

def show
  @customer = Customer.find(params[:id])
  @connection = Connection.all(where connection.site.customer_site.customer.id == params[:id])
  respond_to do |format|
    format.html # show.html.erb
    format.json { render json: @customer }
  end
end

显然@connection 部分不正确,我只是不确定我需要在其中放入什么才能正确链接记录...

【问题讨论】:

  • 您的关系是否使用has_many :through 语法?如果是这样,您也许可以稍微简化您的搜索。发布您的关系,以帮助我们做出最合适的答案。
  • 不,他们只在每个控制器中使用belongs_tohas_many

标签: ruby-on-rails database view controller relational-database


【解决方案1】:

正如@Matt 在他的评论中提到的,最简单的方法是将has_many 关联与:through 选项一起使用。 您可以在 Rails guides 中阅读更多相关信息。

class Site < ActiveRecord::Base
  has_many :customer_sites, foreign_key: :site_id
  has_many :connections
end

class CustomerSite < ActiveRecord::Base
  belongs_to :site
  belongs_to :customer
end
 
class Customer < ActiveRecord::Base
  has_many :customer_sites, foreign_key: :customer_id
  has_many :sites, through: :customer_sites
  has_many :connections, through: :sites
end

在控制器中:

def show
  @customer = Customer.find(params[:id])
  @connections = @customer.connections
  ...
end

如果不够清楚,请告诉我。

【讨论】:

  • 我已经把它放进去,但是我仍然不知道正确的语法让它在我的视图中显示...
  • 我已经编辑了我的答案。另外,请阅读指南。有更多关于使用关联的信息。
  • 我正在阅读指南,我已经把它放在我的控制器中,我认为仍然有&lt;% @connection.each do |l| %&gt;,但我收到错误undefined method 'each' for nil:NilClass
  • 在我的回答中使用@customer.connections
  • 我有。然后我尝试使用上面的代码在我的视图中引用它,并得到错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-05
相关资源
最近更新 更多