Ruby on Rails: Mass-Assignment on iteration in loop?

爱⌒轻易说出口 提交于 2020-01-03 04:56:06

问题


I'm getting mass-assignment error.

Can't mass-assign protected attributes: 1, 2, 3, 4, 5, 6, 7

These numbers represent the iteration in this loop:

<% (1..7).each do |i| %>
  <%= select_tag "hour[#{i}][day]", options_for_select(days_hours) %>
<% end %>

This is in my model:

attr_accessible :day, :open_time, :close_time

I'm trying to create an array like 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"}
}

And I'm trying to save each iteration in a new row into the database

def create
  @hour = @hourable.hours.new(params[:hour])
end

How do I fix the iteration mass-assignment? or am I doing this all wrong?

Thanks!


回答1:


From the hash, Active Record assumes that '1', '2' and '3' are column names OR attributes of the Model and as you have not specified attr_accessible option for the accessing columns, it is throwing mass-assignment error. Otherwise you need to create a hash as follows:

"hour"=>{
"day"=>"Sunday",
"open_time"=>"6",
"close_time"=>"6"}
}

Hope it helps :)




回答2:


Your hour attributes is

"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"}
}

Which means, your hours table should have attributes 1, 2 and 3.



来源:https://stackoverflow.com/questions/23263538/ruby-on-rails-mass-assignment-on-iteration-in-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!