私はRailsの初心者で、今日のほとんどを自分の問題に対する答えを見つけるのに費やしましたが、本当にそれを理解することができませんでした. これは、多くの人が簡単な答えを探している可能性がある一般的な問題だと思います。
私がやりたいことは、collection_select ステートメントを使用し、選択した値を @bno などの変数に格納し、同じ変数を使用して建物に属するプロパティを除外することだけです。
これが私のコードです:
<%= collection_select :property, :buildingnumber, Building.all, :streetno, :streetno, {prompt: "Building Number"},{:class => "form-control"}%>
SO を見回してわかるように、params[:property][:buildingnumber]が選択を保持するはずです。
さらに下に、次のコードがあります。
<% @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%>
これが私が得るエラーです:
/Users//Desktop/JR Buildings/jrbuilding/app/views/properties/index.html.erb を示す Properties#index の NoMethodError で、31 行目が発生しました:
nil:NilClass の未定義メソッド `[]' 抽出されたソース (31 行目付近):
<% @properties.filter_by_building(buildingnumber: Property.find(params[:property][:buildingnumber])).each do |property| %>
Java/Obj C のバックグラウンドを持っているため、ローカル変数をビューに保存する方法に混乱しています。ユーザーが選択した値に基づいてページをフィルタリングするという非常に簡単なことをしたいと考えています。 collection_select。また、どういうわけかページを更新する方法を理解する必要があります。
とにかく役に立つヒントは大歓迎です、事前に感謝します!
また、プロパティ モデルでの filter_by_building コードもお見せしたいと思います。
def self.filter_by_building(opts={})
buildingNo = opts[:buildingnumber]
building = Building.arel_table
self.where(:buildingnumber => buildingNo)
end
本当にありがとう!