1

わかりました、これは私がすべての建物を表示するビューストアを持っているものです。私がやりたいのは、「売り出し中」のステータスの建物だけを見せることです

ビューストアで私は持っています:

<% if notice%>
<p id="notice"> <%= notice%></p>
<%end%>

<h1>All Priorities</h1>

 <%= form_tag  store_path, :method => 'get'  do %>
<p>
  <%=text_field_tag :search , params[:search]%>
  <%= submit_tag "Search", :name=> nil%>
  </p>
  <%end%>

<% if @buildings.present? %> 
 <% @buildings.each do |building| %> 
<div class="entry">
    <div class="img">
    <%= image_tag (building.photo.url)%></div>
    <div class=" disc">
    <h3>Name of the Bulding:  <%= building.title %></h3>
     <h4>Status: <%= building.status %></h4>
    Info: <%=sanitize(building.description)%>
    <div class="price_line">
        <span class="price">Price: <%= sprintf("€ %0.02f",building.price)%></span><br/>
        <div class="button">
        <%= button_to("I want to see it", {:controller => "seeits", :action => "new", :building_id => building.id})%></div>

    </div> 

    <div class="pages">
    <%= will_paginate @buildings %></p>
    </div>

    </div>
<% end %>

</div>

<% else %> does not much try another name<% end %>

controller>buildings_controllerで

 def index 

    @buildings = Building.all

      respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @buildings }
    end

  end


  # GET /buildings/1
  # GET /buildings/1.json
  def show
    @building = Building.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @building }
    end
  end

IFステートメントでそれを行うことはありますか?または私は変更する必要があり<% @buildings.each do |building| %>ますか?

4

1 に答える 1

3

建物のリストをフィルタリングする最も簡単な方法は、ビューでフィルタリングすることです。

@buildings.select{|b| b.status == "for sale"}.each do |building|

ただし、これでもすべてのアイテムについてDBにクエリを実行する必要があります。これは非効率的です。あなたの見解は可能な限り単純でなければなりません、そしてこれは物事を行うためのDRYRailsの方法ではありません。

より堅牢な方法はwhere、コントローラーで句を使用することです。

@buildings = Building.where("status = 'for sale'")

ただし、これでもコントローラーにロジックが多すぎます。モデルは、すべてのクエリロジックを処理できる必要があります。最良の方法は、モデルにRailsスコープを作成することです。Building

class Building < ActiveRecord::Base
  ...
  scope :for_sale, where(:status => "for sale")
  ...
end

次に、コントローラー(またはビュー)で実行する必要があるのは次のとおりです。

@buildings = Building.for_sale
于 2012-09-29T16:07:04.703 に答える