Я следую этому учебному пособию http://pullmonkey.com/2008/03/30/dynamic-select-boxes-ruby-on-rails/, а также интегрирует пример с высоким качеством из
Вот контроллер:
class TestItController < ApplicationController
def index
@genres = Genre.find(:all)
@artists = Artist.find(:all)
@songs = Song.find(:all)
end
def update_artists
# updates artists and songs based on genre selected
genre = Genre.find(params[:genre_id])
artists = genre.artists
songs = genre.songs
render :update do |page|
page.replace_html 'artists', :partial => 'artists', :object => artists
page.replace_html 'songs', :partial => 'songs', :object => songs
end
end
def update_songs
# updates songs based on artist selected
artist = Artist.find(params[:artist_id])
songs = artist.songs
render :update do |page|
page.replace_html 'songs', :partial => 'songs', :object => songs
end
end
end
Здесь модели:
class Genre < ActiveRecord::Base
has_many :artists
has_many :songs, :through => :artists
end
class Artist < ActiveRecord::Base
has_many :songs
end
Вот представление: index.html.erb
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="contain" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<script type="text/javascript">
$(function () {
$('#contain').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2014'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [
['Firefox', 45.0],
['IE', 26.8],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
},
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
}]
});
});
</script>
<%= collection_select(nil, :genre_id, @genres, :id, :name,
{:prompt => "Select a Genre"},
{:onchange => "#{remote_function(:url => {:action => "update_artists"},
:with => "'genre_id='+value")}"}) %>
<div id="artists"><%= render :partial => 'artists', :object => @artists %></div>
<div id="songs"><%= render :partial => 'songs', :object => @songs %></div>
Частицы _artists (_artists.html.erb):
<%= collection_select(nil, :artist_id, artists, :id, :name,
{:prompt => "Select an Artist"},
{:onchange => "#{remote_function(:url => {:action => "update_songs"},
:with => "'artist_id='+value")}"}) %>
Частицы _songs (_songs.html.erb):
<%= collection_select(nil, :song_id, songs, :id, :title,
{:prompt => "Select a Song"}) %>
Я получил эту ошибку при выборе Gnre:
Uncaught ReferenceError: Ajax is not defined
onchange
Пожалуйста, кто-нибудь может мне помочь в этом:
Я провел 3 месяца и до сих пор не нахожу ответа.
Кажется, это конфликт между jquery.min и событием onchange из combobox.
Ajax определен в prototypejs. Вы должны включить сценарий прототипа перед кодом с помощью Ajax. http://prototypejs.org/
Поместите код jQuery в этот LINE $(document).on('ready', function(){})
snippet, это может быть проблемой, " Ajax function not defined
" - это проблема с областью или неправильным jquery
prototype
библиотеки? Вам это понадобится, потому что Rails 2 использовалprototype
в качестве javascript libraray по умолчанию, а помощникremote_fuinction
использует код javascript прототипа.