【问题标题】:showing table twice in partial rails在部分导轨中显示表格两次
【发布时间】:2013-07-08 23:28:24
【问题描述】:

Rails 新手,我想我可能在这里忽略了一些非常简单的事情,但是我在部分中显示了两次表格,不确定这是否与我的关联有关。

这是属性控制器:

class PropertiesController < ApplicationController
  before_filter 

  def index
    @property= Property.all
  end

  def new
    @property = current_user.property.build if signed_in? 
  end

  def show
    @property = current_user.property.paginate( params[:page])
  end

这是用户控制器:

class UsersController < ApplicationController
  before_filter :authenticate_user!

  def index
    authorize! :index, @user, :message => 'Not authorized as an administrator.'
    @users = User.all
  end

  def show
    @user = User.find(params[:id])
    @property = @user.property.paginate(page: params[:page])
  end

以下是模型中的关联: 用户模型:

class User < ActiveRecord::Base
  has_many :property, dependent: :destroy

属性:

class Property < ActiveRecord::Base
  attr_accessible :address, :name
  belongs_to :user 

这里是_property.html.erb 部分

<li>
  <table>                         
    <tr>                          
      <th>Name</th>
      <th>address</th>
    </tr>
    <% @user.property.each do |property| %> 
    <tr>
      <td><%= property.name %></td>  
      <td><%= property.address %></td> 
    </tr>
    <% end %>                        
  </table>
</li>             

这里是show.html.erb

<div class="row">
   <aside class="span4">
      <section>
         <h1>
           My Properties 
         </h1>
      </section>
   </aside>

   <div class="span8">
     <% if @user.property.any? %>
       <h3>Properties (<%= @user.property.count %>)</h3>
         <ol>
           <%= render @property %>
         </ol>
         <%= will_paginate @property %>
     <% end %>
   </div>
</div>

这是在浏览器中呈现的内容。 http://i.imgur.com/SlilDo3.png

让我知道是否还有其他对这个问题有帮助的。感谢所有回复。

【问题讨论】:

  • 在您的用户模型中,您应该使用has_many :properties 而不是has_many :property。
  • “SQL 日志”的第二部分看起来只是显示控制台交互。您还打算展示其他东西吗?
  • 试图用图像编辑问题不允许我这样做,因为 i.imgur.com/SlilDo3.png
  • 更改为属性到属性,仍然有同样的问题。

标签: ruby-on-rails database view associations partials


【解决方案1】:

在@property = Property.all 的位置,您正在设置Property 类的实例集合......显然这个集合中的内容不止于此。

当你使用时

render @property

它将为集合中名为@property 的每个项目呈现_property 模板 即使您在 _property 模板中使用 user.property.each - 那意味着您实际上是在说:

对于@property 中的每个属性,渲染模板_property... 和 每次你这样做时,渲染一个新的表格,为表格行 user.property 中的每个属性。

如果您只想要一个表格,并且只需要为属性列表中的每个单独的“属性”渲染每一行,称为@property,那么您需要将表格拉到渲染之外。

例如:

   <h3>Properties (<%= @user.property.count %>)</h3>
       <table>                         
       <tr>                          
         <th>Name</th>
         <th>address</th>
       </tr>
       <%= render @property %>
       </table>

和_property:

<tr>
  <td><%= property.name %></td>  
  <td><%= property.address %></td> 
</tr> 

【讨论】:

    猜你喜欢
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    相关资源
    最近更新 更多