0

初学者正在运行 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 关联?)我的 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 的新手。

4

2 回答 2

1

改变

attr_accessible :concierge, :hotel_id, :room24h

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

Facility

于 2012-04-15T22:29:06.710 回答
0

尽管我已经过去了很多时间,但我还是更改了与 HABTM 的关系,更改了模型和控制器并且它起作用了。我相信这是因为它是一个 has_one 关系。它需要是一个NN关系。

于 2012-06-05T14:56:00.763 回答