2014-07-13 2 views
0

나는 호텔 클래스의 주소가 지정된 개체가 있습니다. 양식을 사용하여 데이터를 저장하려고하면 모든 내용이 저장됩니다. 주소 제외한 모든 주소. 아무 오류도, 아무것도 ... 다른 변종을 시도, 도와주세요. 여기 rails 데이터베이스에 직렬화 된 개체를 저장할 수 없습니다.

내 코드입니다 : 당신의 hotels_controller.rb에서

마이그레이션

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 %> 
+0

나를 위해 나는 belongs_to 호텔 (물론, 호텔 has_one 주소) 별도의 모델 주소를 생성합니다. IMHO,이 방법은 덜 복잡합니다. – RedZagogulin

+0

@ Red Zagogulin, 더 쉽게 보입니다. 그럼 호텔 주소가 포함 된 새 테이블 주소가 필요할 것 같네요, 그렇죠? –

+0

예. 호텔 "has_one"주소 및 주소 "belongs_to"호텔, 그러므로 호텔 테이블 - address_id, 주소 테이블 - hotels_id. – RedZagogulin

답변

1

당신이 허용 된 주소 매개 변수?

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