【问题标题】:rails How to save a serialized hashrails 如何保存序列化的哈希
【发布时间】:2014-09-04 17:13:16
【问题描述】:

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

#model hotel

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

...并查看“新”

<%= 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 address nil...

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

# 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 这是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

【问题讨论】:

  • 回答您的问题,第一种方法是正确的。这是带有文档的明确答案。 stackoverflow.com/a/21397522/1536309 - 如果您在酒店控制器的def create 内使用puts params,您应该能够看到所有通过的参数。确保你有地址参数。

标签: ruby-on-rails serialization


【解决方案1】:

迁移文件的第一件事是确保将字段保存为测试,例如

def self.up
   add_column : hotels, : address, :text
end

然后 Rails 会为您将其转换为 YAML / Hash(并执行适当的序列化)。

祝你好运。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    • 2018-05-16
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    • 2016-08-11
    相关资源
    最近更新 更多