rails无法将序列化对象保存在数据库中

时间:2014-07-13 12:43:59

标签: ruby-on-rails serialization

我有一个序列化对象:酒店类中的地址。当我尝试使用表单保存数据时,一切都保存得很好。所有除外:地址。没有错误,没有......试过不同的变种,请帮忙。

这是我的代码:

迁移

class CreateHotels < ActiveRecord::Migration
  def change
    create_table :hotels do |t|
      t.string  :title
      t.integer :user_id
      t.integer :stars
      t.text    :room
      t.decimal :price
      t.text    :address

      t.timestamps
    end
    add_index :hotels, [:user_id, :created_at]
  end
end

hotel.rb

class Hotel < ActiveRecord::Base

  belongs_to :user
  default_scope -> { order('created_at DESC') }
  validates :title, presence: true, length: { maximum: 80 }
  validates :stars, presence: true
  validates :room, length: { maximum: 800 }
  validates :user_id, presence: true
  serialize :address, Hash
end

new.html.erb

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

  <%= f.label :title %>
  <%= f.text_field :title %>

  <%= f.label :stars %>
  <%= f.text_field :stars %>

  <%= f.label :room, "Room description" %>
  <%= f.text_area :room, size: "20x10" %>

  <%= f.label :price %>
  <%= f.number_field :price %>

  <%= f.fields_for :address, OpenStruct.new(f.object.address || {}) do |o| %>
    <%= o.label :country %>
    <%= o.text_field :country %>

    <%= o.label :state %>
    <%= o.text_field :state %>

    <%= o.label :city %>
    <%= o.text_field :city %>

    <%= o.label :street %>
    <%= o.text_field :street %>
  <% end %>
<% end %>

1 个答案:

答案 0 :(得分:1)

在您的hotels_controller.rb中,您是否允许使用地址参数?

    params.require(:hotel).permit(address: [:country, :state, :city, :street])