简体   繁体   中英

specific view on ruby on rails

ok here is the thing i have the view store that shows all the buildings. all i want to do is to show me only the buildings with the status "for sale"

in views store i have:

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

in 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

is there to do it with IF statement ? or i have to change <% @buildings.each do |building| %> <% @buildings.each do |building| %> ?

The simplest way to filter your list of buildings would be to filter it in your view:

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

However, this still requires you to query the DB for all your items - which is inefficient. Your views should be as simple as possible, and this isn't the DRY Rails way to do things.

A more robust way would be to use a where clause in your controller:

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

However, this still puts too much logic in your controller. Your model should be able to handle all of the query logic for you. The best way would be to create a Rails scope on your Building model:

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

Then, in your controllers (or views) you would only have to do:

@buildings = Building.for_sale

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM