I'm Rails newby, and I spent most of today trying to find an answer to my problem, but I couldn't really figure it out. I think this is a common problem a lot of people may be looking for straightforward answer, so here goes:
All I want to do is use a collection_select statement, store the selected value in a variable like @bno, and use that same variable to filter out the properties that belong to a building.
Here's my code:
<%= collection_select :property, :buildingnumber, Building.all, :streetno, :streetno, {prompt: "Building Number"},{:class => "form-control"}%>
As I understand it from looking around SO, params[:property][:buildingnumber] should now hold my selection.
Now further down, I have this code:
<% @properties.filter_by_building(buildingnumber: Property.find(params[:property][:buildingnumber])).each do |property| %>
<div class="col-sm-6 col-md-4">
<div class="thumbnail relative">
<%= image_tag property.avatar.url(:medium) %>
<div class="caption fixedtextheight">
<h4>Building No: <%= property.buildingnumber%></h4><h4>Property No: <%= property.number%></h4>
<p><h5>Rented: <%=property.rented%></h5></p>
<p>
<a type="button" class="btn btn-default navbar-btn" href=<%= edit_property_path(property) %>>Edit</a> <%= link_to "Delete", property, method: :delete, :class=>"btn btn-default navbar-btn", data: { confirm: "Deleting this property will delete ALL the tenants, expenses, and leases associated to it."} %>
</p>
</div>
</div>
</div>
<%end%>
Here is the error I get:
NoMethodError in Properties#index Showing /Users//Desktop/JR Buildings/jrbuilding/app/views/properties/index.html.erb where line #31 raised:
undefined method `[]' for nil:NilClass Extracted source (around line #31):
<% @properties.filter_by_building(buildingnumber: Property.find(params[:property][:buildingnumber])).each do |property| %>
I'm confused by how I should save local variables in views, as I'm coming from a Java/Obj C background, and I want to do something very simple, which is to filter the page based on the value the user selects in a collection_select. Also I need to figure out how to update the page somehow.
Anyway helpful tips much appreciated, thank you in advance!
Also want to show you my filter_by_building code in my property model:
def self.filter_by_building(opts={})
buildingNo = opts[:buildingnumber]
building = Building.arel_table
self.where(:buildingnumber => buildingNo)
end
Thanks so much!