0

Newbie to rails, I think i might be overlooking something very simple here, but I am displaying a table twice in a partial, not sure if it's to do with my associations.

Here is the Properties controller:

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

Here is the Users Controllers:

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

Here are the associations in the models: user model:

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

property:

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

Here is the _property.html.erb partial

<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>             

Here is the 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>

This is what is rendered in the browser. http://i.imgur.com/SlilDo3.png

Let me know if there is anything else will be of help with this question. All responses appreciated.

4

1 回答 1

0

你在哪里@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> 
于 2013-07-10T07:30:10.610 回答