LearningRoR
LearningRoR

Reputation: 27222

Search LIKE? only if it meets a certan requirement?

Please excuse any of my terminology if its off. In my model I am trying to define a method that would search 2 columns unless another column(boolean) is true.

class BusinessStore < ActiveRecord::Base
  attr_accessible :business_name, :address, :online_store, :website

  def store
    "#{business_name} - #{address}" 
  end
end

:business_name is a virtual attribute, :online_store is a boolean column.

I want to take the :online_store and make a method like this:

def store
 "#{business_name} - #{address}" unless business_store.online_store = true
end

So it shouldn't show Business Stores that are flagged as true for being online stores because I am looking for Retail stores only; stores with addresses. Here is my model controller. Just to clarify again, BusinessStore.where should omit searching stores with online_store = true

class BusinessStoresController < ApplicationController

  def index
    @business_stores = BusinessStore.all
    @business_stores = BusinessStore.where("address like ?", "%#{params[:q]}%")

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @business_stores }
      format.json { render :json => @business_stores.collect{|b|{:id => b.id, :name => b.store } } }
    end
  end
end

This isn't working becuase my business_stores.json gets a NameError:

http://localhost:3000/business_stores.json
NameError in BusinessStoresController#index

undefined local variable or method `business_store' for...

How do you define this?

Upvotes: 1

Views: 114

Answers (1)

Frans
Frans

Reputation: 1448

You're kind of asking for two different things I think. If you want to fetch all physical stores where online_store != true, you could just define a scope for it.

class BusinessStore < ActiveRecord::Base
  attr_accessible :business_name, :address, :online_store, :website
  scope :stores, where(:online_store => false)
  # or alternately
  scope :alternate_stores, where("online_store IS NOT NULL")
  # depending on default values
end

That doesn't exclude it from the where() method however. You COULD overload that method, but I don't think this situation calls for that.

def store
  "#{business_name} - #{address}" unless business_store.online_store = true
end

The above code works just fine, if that's what you want (see what I mean about asking for two things?). You just need to change it to

"#{business_name} - #{address}" unless self.online_store == true

The error your seeing is because you don't have an object named business_store, you should access the variable on the object itself instead. And you need double =, otherwise you're actually setting the variable to true, which in Ruby will be true in the eyes of the if/unless as well.

Upvotes: 2

Related Questions