Creating form for associated has_many model
I have a 'Business' model which has_many 'Hours'. Each Hour record has a start_time and an end_time, and there's an Hour record for each day of the week for a given business.
I have a form where I only update the hours for a business -- nothing else about the business. In that case it makes sense to have the Hours controller do the updating. But I can't figure out exactly how to set the form up correctly.
Here's what I have so far, but with each hour sent as a param, I need to 开发者_运维知识库know if it's the start_time or end_time and which day it's associated with. In the select_tag, hour.day contains an integer 0-6 which represents a day of the week (Sunday through Saturday).
=form_tag({:controller => 'hours', :action => "update_multiple"}, :remote => :true) do |f|
-business.hours.each do |hour|
=fields_for hour do |hour_fields|
=select_tag 'hour[days_nums][#{hour.day}]', options_for_select(possible_hours, :start_time)
class Business < ActiveRecord::Base
has_many :hours, :as => :hourable
accepts_nested_attributes_for :hours
end
class Hour < ActiveRecord::Base
belongs_to :hourable, :polymorphic => true
end
create_table "hours", :force => true do |t|
t.integer "hourable_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "hourable_type"
t.integer "day"
t.time "start_time"
t.time "stop_time"
end
How can I set this up? Thanks!
I don't know haml at all, but I'll try
You should work with it through BuisnessController
. Here is form for new
and edit
action:
=form_for @buisness do |f|
=f.fields_for :hours do |hour|
=hour.select :day, (0..6)
=hour.select :start_time, [6,7,8] # some start times
=hour.select :stop_time, [9,10,11] # some stop times
fl00r, you definitely got me to this solution, you made me realize that I should use the form_for @business, however I just needed to change the controller and action:
-form_for @business, :url => {:controller => 'hours', :action => "update_multiple"}, :remote => :true do |f|
=f.fields_for :hours do |hour|
=hour.select :day, (0..6)
=hour.select :start_time, [6,7,8] # some start times
=hour.select :stop_time, [9,10,11] # some stop times
精彩评论