Reputation: 38902
I have two model objects which are Event
and Task
, they have one-to-many association.
Event model:
class Event < ActiveRecord
has_many :Task
Task model:
class Task < ActiveRecord
belongs_to :Event
My controller has a index function which return the list of events (@events), Maybe return also a list of tasks(@tasks):
class MyController < ApplicationController
def index
@events = Event.all
@tasks.....
end
In my view (index.html.haml), I have defined a multi-select field for all events in a table column as below:
%td
=select_tag('events',options_from_collection_for_select(@events, 'id', 'name'), {:multiple=>'multiple'})
the output code of the above select_tag is:
<td>
<select id="events" multiple="multiple" name="events">
<option value="1">Event 1</option>
<option value="2">Event 2 </option>
</select>
</td>
What I want is in another table column I have another multi-select field for tasks which looks just like the events multi-select field, BUT the key feature is that, the content of the tasks select options is dynamically changed based on which event or events user selected from the events multi-select field.
For example, suppose event_1 is associated with task_1 and task_2, if user mouse click on event_1, the tasks multi-select field will show task_1 and task_2 as options which is available for user to select next.
How to implement this feature in rails? I am using Rails 3. I guess this feature needs some ajax magic to play, but I have no idea how to implement it, it is better if someone can give a simple example on this issue. Thanks!
Upvotes: 0
Views: 3061
Reputation: 3027
Check this example is exactly what you need for your models http://pullmonkey.com/2008/03/30/dynamic-select-boxes-ruby-on-rails/.
And I would recommend you to keep a logic for your models.What I mean is
class Event < ActiveRecord
has_many :tasks # also notice...no capital "t"
end
Same for Task model
Upvotes: 2