Within my house table I have a postcode for each house. I also have an index view for my housing table that contains a table which contains headings such as 'Name', 'Address', 'State'. I was looking to integrate a text_field_tag that would allow user's to input the 9 digits of a postcode in order to filter the table to only show the house with that postcode. However, I also want the user to be able to input the first 4 digits of their postcode e.g. '7644' and it would display all houses that begin with '7644' e.g. two records one with the postcode of the '76444-5645' and '76443-123'. Ideally I would apply logic through my '@search' variable within my houses controller. However I am up to any ideas or tips.
In order to instantiate the house model I would use @house = House.all
I'll be honest I don't know where to begin with this. I have arel_sql in my system so I assume that would be used to query for the search.
CodePudding user response:
It depends on how your models/controllers are defined but you're probably looking for the SQL operator LIKE
'%', which allows you to search for a pattern in a given column. Example:
LIKE Operator | Description |
---|---|
WHERE CustomerName LIKE 'a%' | Finds any values that start with "a" |
Assuming you're using ActiveRecord and your model is House
, it wouldn't event need to instantiate all houses. Your code would look something like this:
postcode = '7644'
@houses = House.where('postcode LIKE ?', "#{postcode}%") # this returns where the postcode starts with '7644'