Ruby on Rails - 批量分配问题

时间:2012-04-15 22:06:13

标签: ruby-on-rails associations mass-assignment

Begginer Running rails 3.2.2,Ruby 1.8.7

我有2个模型,一个酒店(由脚手架创建)和设施(有空控制器)。 我能够设置1对1关联和siplaying字段,但似乎无法将其插入数据库中。 我得到了:

ActiveModel::MassAssignmentSecurity::Error in HotelsController#create
Can't mass-assign protected attributes: @hotel
app/controllers/hotels_controller.rb:48:in 'new'
app/controllers/hotels_controller.rb:48:in 'create'

- >我的模特是:

class Hotel < ActiveRecord::Base
  has_one :facility, :dependent => :destroy
  accepts_nested_attributes_for :facility, :allow_destroy => true
  attr_accessible :name, :rating, :recommended, :facility_attributes
end

class Facility < ActiveRecord::Base
  belongs_to :hotel
  attr_accessible :concierge, :hotel_id, :room24h
end

正如我所说,我的设施控制器是空的(它可以,对吧?因为我与酒店联系?) 我的hotel_controller是创建脚手架后的默认设置,只添加了1行:

 def new
    @hotel = Hotel.new
    @hotel.build_facility  #-->I added this only, I searched and all i found was this

    respond_to do |format|
      format.html # new.html.erb
      format.json { render :json => @hotel }
    end
  end

 def create
    @hotel = Hotel.new(params[:hotel])

    respond_to do |format|
      if @hotel.save
        format.html { redirect_to @hotel, :notice => 'Hotel was successfully created.' }
        format.json { render :json => @hotel, :status => :created, :location => @hotel }
      else
        format.html { render :action => "new" }
        format.json { render :json => @hotel.errors, :status => :unprocessable_entity }
      end
    end
  end

最后,我的表格html是:

<%= form_for(@hotel) do |f| %>

<div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :rating %><br />
    <%= f.number_field :rating %>
  </div>
  <div class="field">
    <%= f.label :recommended %><br />
    <%= f.check_box :recommended %>
  </div>
  <br />

    <h2>Hotel Facilities</h2>

    <%= f.fields_for :@hotel do |facility_fields| %>
 <div class="field">
    <%= facility_fields.label :room24h, "24h Room Service:" %>
    <%= facility_fields.check_box :room24h %>
  </div>
 <div class="field">
    <%= facility_fields.label "Concierge:" %>
    <%= facility_fields.check_box :concierge %>
  </div>
<%end%>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

我在创建时遇到的错误是问题的开始。我应该添加更多代码吗?hotel_controller?会是什么呢?另外,我还需要为编辑/更新做更多的代码吗?

提前致谢并抱歉,我是RoR的新人。

2 个答案:

答案 0 :(得分:1)

更改

attr_accessible :concierge, :hotel_id, :room24h

attr_accessible :concierge, :hotel_id, :room24h, :hotel
Facility

中的

答案 1 :(得分:0)

即使我已经过了很多时间,我还是将关系更改为HABTM,更改了模型和控制器,并且工作正常。 我相信这是因为它是一种无关紧要的关系。它需要是一个N-N关系。