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

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

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.



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