问题
I have a loop in a form and I'm trying to create multiple data with same name but I'm getting an error with my syntax.
I had another question to the same application HERE where I had a mass-assignment error because of the numbers in the array
<%= form_for [@hourable, @hour] do |f| %>
<% (1..7).each do |i| %>
<%= select_tag "hour[#{i}][day]", options_for_select(days_hours) %>
<%= select_tag "hour[#{i}][open_time]", options_for_select([ ... %>
<%= select_tag "hour[#{i}][open_time]", options_for_select([ ... %>
<% end %>
<% end %>
Which is coming from [#{i}]
. So I tried removing this, because I thought it would give me this array:
"hours" =
[{"day"=>"Sunday","open_time"=>"6", "close_time"=>"6"},
{"day"=>"Monday","open_time"=>"6", "close_time"=>"6"},
{"day"=>"Tuesday","open_time"=>"6", "close_time"=>"6"}]
Originally I had this:
"hour"=>{
"1"=>{"day"=>"Sunday","open_time"=>"6","close_time"=>"6"},
"2"=>{"day"=>"Sunday","open_time"=>"6","close_time"=>"6"},
"3"=>{"day"=>"Sunday","open_time"=>"6","close_time"=>"6"}
}
How do I get to the correct array?
Thanks!
Edit:
Controller:
class HoursController < ApplicationController
before_filter :get_hourable
def new
@hour = @hourable.hours.new
end
def create
@hour = @hourable.hours.new(params[:hour])
end
private
def get_hourable
@hourable = params[:hourable].camelize.constantize.find_by_user_id(current_user)
end
def hourable_id
params[(params[:hourable].singularize + "_id").to_sym]
end
end
day_hours in my helper
def days_hours
[
['Sunday', 'Sunday'],
['Monday', 'Monday'],
['Tuesday', 'Tuesday'],
['Wednesday', 'Wednesday'],
['Thursday', 'Thursday'],
['Friday', 'Friday'],
['Saturday', 'Saturday']
]
end
This is my model:
class Hour < ActiveRecord::Base
attr_accessible :day, :open_time, :close_time, :days_attributes
include IceCube
belongs_to :hourable, polymorphic: true
belongs_to :professional
serialize :schedule, Hash
serialize :hour, Hash
end
回答1:
Try this:
<%= form_for [@hourable, @hour] do |f| %>
<% 7.times do %>
<%= select_tag "hour[][day]", options_for_select(days_hours) %>
<%= select_tag "hour[][open_time]", options_for_select([ ... %>
<%= select_tag "hour[][close_time]", options_for_select([ ... %>
<% end %>
<% end %>
Starting with hour[]
generates an array within params[:hour]. Each element in the array will have the keys after hour[]
- in this case, :day
, :open_time
, and :close_time
.
来源:https://stackoverflow.com/questions/23272276/ruby-on-rails-receiving-internal-server-error-expected-array-got-string-for-p