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

在控制器>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|

但是,这仍然需要您为所有项目查询数据库 - 这是低效的。您的视图应该尽可能简单,这不是DRY Rails 做事的方式。

更强大的方法是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 回答