Querying Multi Database Tables and displaying in index.html.erb

My Schema.rb is below

ActiveRecord::Schema.define(version: 2019_05_27_040649) do

create_table “days”, force: :cascade do |t|

t.integer “season_id”

t.datetime “created_at”, null: false

t.datetime “updated_at”, null: false

t.date “raceday”

t.index [“season_id”], name: “index_days_on_season_id”

end

create_table “points”, force: :cascade do |t|

t.text “place”

t.text “riders”

t.integer “racepoints”

t.text “status”

t.integer “race_id”

t.datetime “created_at”, null: false

t.datetime “updated_at”, null: false

t.index [“race_id”], name: “index_points_on_race_id”

end

create_table “races”, force: :cascade do |t|

t.boolean “display”

t.text “racename”

t.integer “season_id”

t.integer “day_id”

t.datetime “created_at”, null: false

t.datetime “updated_at”, null: false

t.text “raceclass”

t.index [“day_id”], name: “index_races_on_day_id”

t.index [“season_id”], name: “index_races_on_season_id”

end

create_table “seasons”, force: :cascade do |t|

t.date “year”

t.datetime “created_at”, null: false

t.datetime “updated_at”, null: false

end

end

I want to end up with something like this for the race index.html.erb file

You select the season it then displays the days for the the selected season. You then select the day and the races for that day are displayed.

The four tables are joined and the results is displayed in the Race Details.

My current points index.html is this.

<%= notice %>

Points

Season

<%= collection_select(:season, :id, Season.all, :id, :year, {}, {:multiple => false}) %>


Race Day

<%= collection_select(:day, :id, Day.all, :id, :raceday, {}, {:multiple => false}) %>


Race Name

<%= collection_select(:race, :id, Race.all, :id, :racename, {}, {:multiple => false}) %>



I am thinking of using a grouped_collection_select to populate the relevant dropdowns . I know I need to Jquery or javascript to pass the selected options from one drop down to another .but can’t get it to work

Cheers Dave

The way I start doing this is to decompose the view into partials, at least one per picker. Make sure that each partial after the first one takes an argument (allowed to be null) indicating what the previous picker chose. If there is no argument passed, the picker is rendered with no options. Next, you need to add controller, with a route per picker, and either write unobtrusive JS event listeners, or add long-hand onchange arguments to your picker to trigger the next picker.

f.collection_select :picker_one, @picker_one_options, :name, :id

$(document).on('change', '#picker_one', function(evt){
  $('#picker_two_holder').load('/pickers/picker_two/' + $(this).val());
});

In the pickers_controller, you'd have a method like

def picker_two
  @picker_two_options = Option.find(params[:id]).children
  render partial: 'picker_two', layout: false
end

Each picker then loads the next one, and finally, the surrounding form is submitted with all the dynamic pickers within it.

Let me know if any of this is too cryptic.

Walter

Thanks Walter

Hi Walter can you please give me a better understanding of this as I can’t quite follow it.

Cheers Dave

Hi Can I just do rails g controller Pickers?

How do I get the route for this as not one is made?

Cheers Dave

Yes, that's how you would get the pickers controller, if that's how you want to model this. You could also use your existing controller for the object in question (I've forgotten the names of things in your original app). If you had a widgets_controller, you could make a method in that for each of your pickers. Your route would change depending on which approach you chose. To add the route, you would open your routes file and add the appropriate declaration there:

(assuming you were using pickers_controller#picker_two)

resources :pickers, only: [] do
  collection do
    get :picker_two, to: 'pickers#picker_two'
    get :picker_three, to: 'pickers#picker_three'
  end
end

(If you already had a widgets_controller, and wanted to add on)

resources :widgets do
  collection do
    get :picker_two, to: 'widgets#picker_two'
    get :picker_three, to: 'widgets#picker_three'
  end
end

Then run 'rake routes' to see what those routes get named. Note that because these are "collection" routes, they won't pass the ID as I had noted in my example previously. You'd have to pass that as a querystring variable, so your link would be something like /widgets/picker_two?parent=42, and you'd have to allow the parent argument in your safe_params, and then get it with params[:parent] rather than relying on the id.

Most flexible of all would be to use match rather than a resource-based route:

match 'picker_two/:id', to: 'pickers#picker_two', via: :get, as: :picker_two

That would get you a very specific named route that would fit with my original example.

All of this is covered in great detail in the excellent guide "Routing from the outside in", at guides.rubyonrails.org

The ultimate answer to your questions is 'you use the framework'. All the tools are there for you to build whatever you want, or whatever makes sense to you.

Walter

Thanks

Hi If this is my last table I want to use

create_table “points”, force: :cascade do |t|

t.text “place”

t.text “riders”

t.integer “racepoints”

t.text “status”

t.integer “race_id”

t.datetime “created_at”, null: false

t.datetime “updated_at”, null: false

t.index [“race_id”], name: “index_points_on_race_id”

end

Which references the other tables. Are you saying I could just use this table or do I still need the Pickers controller?

Cheers Dave

What do the pickers mean? What values are they representing? When you choose one picker value, why does another picker need a different set of values to appear? If you can explain how you have modeled that part of your data, then I can help you further. In principle, a controller (any controller) can handle requests related to any model. It's just a convention that if you have a model Foo, you will have a FoosController to handle requests related to that model.

Here's a practical example of how you might use this sort of cascading picker:

class Country < ApplicationRecord
  has_many :states
end

class State < ApplicationRecord
  belongs_to :country
  has_many :cities
end

class City < ApplicationRecord
  belongs_to :state
end

You have a natural cascade of country to state to city, and it makes sense what those relationships are. The relationships are codified with the has_many and belongs_to macros, so it's clear that if you say @state.cities, you will get the cities that exist inside that state. You would do that by establishing what the parent id is in each child record. You might have Arizona as @state id = 1, and then have a bunch of cities like Phoenix: @city id = 22, state_id = 1, so you can gather them up.

So you have choices now as to choosing a controller pattern. The REST design says that you should have a separate controller for each model, and so that could go like this:

class CountriesController < ApplicationController
  def index
    @countries = Country.order(:name)
    render partial: 'countries_picker', layout: false
  end

  def show
    country = Country.find params[:id]
    @states = @country.states.order(:name)
    render partial: 'states_picker', layout: false
  end
end

class StatesController < ApplicationController
  def show
    state = State.find params[:id]
    @cities = @state.cities.order(:name)
    render partial: 'cities_picker', layout: false
  end
end

Your routes would look like this

resources :countries, only: [:index, :show]
resources :states, only: :show

If you wanted to have a single controller concerned with making these pickers (and ignore the whole REST thing), then you could have:

class PickersController < ApplicationController
  def countries
    @countries = Country.order(:name)
    render partial: 'countries_picker', layout: false
  end

  def states
    country = Country.find params[:id]
    @states = country.states.order(:name)
    render partial: 'states_picker', layout: false
  end

  def cities
    state = State.find params[:id]
    @cities = state.cities.order(:name)
    render partial: 'cities_picker', layout: false
  end
end

Your routes could look like this:

match '/countries', to: 'pickers#countries', via: :get, as: :countries_picker
match '/states', to: 'pickers#states', via: :get, as: :states_picker
match '/cities', to: 'pickers#cities', via: :get, as: :cities_picker

See -- there's no rules that say that you have to use one controller for one model, or have a separate controller for each model. Mix and match. Have fun! Rails is flexible.

Walter

That look likes a big help Walter.

Season
<%= collection_select(:season, :id, Season.all, :id, :year, {}, {:multiple => false}) %>

This with <%= collection_select(:season, :id, Season.all, :id, :year, {}, {:multiple => false}) %>

Example

Does this Layout still work in Rails

<%= collection_select(“job”, “client_id” , @clients, “id”, “name”, {},{:onchange => “alert(‘hello’)”} )%>

I want to do something like this.

<%= collection_select(“season”, “season_id” , @seasons, “id”, “year”, {}, {:onchange => “alert(‘selectedDay’)”} )%>?

This would be in the Points Controller

def selectedDay(){

 @raceday  =  SELECT FROM days where day.season_id = [season.id](http://season.id)

 render partial: 'days_picker', layout: false

}

Once I have the season.id that change I want to a sql query to get the relevant days for that season and put that result in the next select statement. Put the result as @selectedDays

partial: ‘days_picker’ referenced from the Points Index view

<%= collection_select(“day”, “day_id” , @days, “id”, "raceday”, {}, {:onchange => “alert(‘selectedRace’)”} )%>

Cheers Dave

Ps Changed

partial: ‘days_picker’ referenced from the Points Index view

<%= collection_select(“day”, “day_id” ,

@selectedDays , “id”, "raceday”, {}, {:onchange => “alert(‘selectedRace’)”} )%>

HI What would the render partial: ‘cities_picker’, layout: false look like in your example?

Assuming you had a states_controller.rb that had a show method in it that looked something like this:

def show
  @state = State.find params[:id]
  render partial: 'cities_picker', layout: false
end

you could have a views/states/_cities_picker.html.erb that looked like this:

<%= select_tag('address[city_id]', options_from_collection_for_select(@state.cities, :id, :name)) %>

That's all you would need to make a fully populated picker with

<select name="address[city_id]">
  <option value="1">Aliquippa</option>
  <option value="2">Allentown</option>
  ...
  <option value="60">York<.option>
</select>

That's assuming you have the data set up and populated so you know that these are the cities in Pennsylvania. You'd possibly put a label or some other HTML in there, but if you were swapping out this form element for one populated with the cities of Ohio, then you'd probably what to move as little around as necessary, and just leave the label and any structural HTML untouched in the parent page.

Walter