Answer the question
In order to leave comments, you need to log in
How to display records with a specific value (from select)?
There are 2 entities:
class Ad < ActiveRecord::Base
belongs_to :city
attr_accessible :title, :text, :number, :published_date, :city_id
end
class City < ActiveRecord::Base
has_many :ads
attr_accessible :name, :ad_id
end
<h1>Список объявлений</h1>
<%= link_to 'Новое объявление', new_ad_path %><br/><br/>
<%= label :city, 'Город: ' %>
<%= collection_select(:ad, :city_id, City.all, :id, :name, prompt: 'Выберете город...') %><br/>
<br/>
<table>
<% @ads.each do |ad| %>
<h2><%= link_to ad.title, ad %></h2>
<%= ad.text %><br/>
<strong>Город: </strong><%= ad.city.name %><br/>
<strong>Дата публикации: </strong><%= ad.created_at %>
<% end %>
</table>
<br/>
<%= will_paginate @posts%>
Answer the question
In order to leave comments, you need to log in
1. We send a request when an element is selected from the select:
The request goes to the ads_path (that is, the index action of the ads controller), the city id is passed in the ad[city_id] parameter.
2. In the action, return the list of city announcements:
respond_to :json
def index
@city = City.find(params[:ad][:city_id])
respond_with @ads = @city.ads
end
$ ->
$("#ad_city_id").on "ajax:success", (e, data, status, xhr) ->
objects = xhr.responseJSON
Luckily I'm not familiar with Rails. But on angular.js, this is done elementarily thanks to bindings. I recommend looking in his direction. As far as I remember, rail has a REST-only Api project with truncated controllers and without AcriveRecord. Pay attention to it.
Specifically for your situation. When you select a city in the select field, you will have to make a request to the server to get cities and display them as you are doing now. If the relationship is 1:m or just display the value if 1:1. And of course, when loading by default the city in select, you should already have the associated entry pulled up.
Good luck!
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question