rails如何保存序列化哈希

时间:2014-07-14 17:37:51

标签: ruby-on-rails serialization

我在酒店模型中有一个序列化对象 :address,我不知道如何在数据库中正确保存它。我有以下内容:

#model hotel

class Hotel < ActiveRecord::Base
belongs_to :user
serialize :address, Hash
end

...并查看&#39; new&#39;

<%= 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 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 %>

  <%= f.submit "Create hotel", class: "btn btn-large btn-primary" %>
<% end %>

使用此代码我得到的是:酒店地址无 ...

好的..我们会走另一条路。谷歌搜索后,我来到这个代码:

# hotel.rb model

class Hotel < ActiveRecord::Base

  class Address
    include ActiveModel::Conversion
    extend ActiveModel::Naming

    attr_accessor :country, :state, :city, :street

    def persisted?; true end

    def id; 1 end

    def self.load json
      obj = self.new
      unless json.nil?
        attrs = JSON.parse json
        obj.country = attrs['country']
        obj.state = attrs['state']
        obj.city = attrs['city']
        obj.street = attrs['street']
      end
      obj
    end

    def self.dump obj
      obj.to_json if obj
    end  
  end

  belongs_to :user
  serialize :address, Address
end

和相同的视图new.html.erb

结果是:地址:0xb0e530c

所以,数据库中没有任何东西可以保存......我不知道下一步该尝试什么,我会感激任何帮助。我不知道序列化对象会给我带来太多问题。 谢谢!

PS Here's hotels_controller。

class HotelsController < ApplicationController
  before_action :signed_in_user, only: [:index, :edit, :update, :destroy]


  def new
    @hotel = Hotel.new
  end

  def index
    @hotels = Hotel.paginate(page: params[:page])
  end

  def show
    @hotel = Hotel.find(params[:id])
  end

  def create
    @hotel = current_user.hotels.build(hotel_params)    
    if @hotel.save      
      flash[:success] = "Hotel created!"
      redirect_to @hotel
    else
      render 'new'      
    end    
  end

  private

    def hotel_params
      params.require(:hotel).permit(:title, :stars, :room, :price, :address)
    end

end

1 个答案:

答案 0 :(得分:1)

迁移文件中的第一件事就是确保将字段保存为

之类的测试
def self.up
   add_column : hotels, : address, :text
end

然后Rails会将它转换为YAML / Hash(并执行正确的序列化)。

祝你好运。祝你好运。

PS看看https://stackoverflow.com/a/6702790/1380867