2012-03-09 48 views
0

我嘗試了很多方法,以一種很好和乾淨的方式關聯這些模型,但像往常一樣,任何初學者我都在做一些我看不見的蠢事。請,有人可以幫我嗎?如何關聯這些模型?

用戶模型

class User < ActiveRecord::Base 
    has_one :house, :dependent => :destroy 
    accepts_nested_attributes_for :house, :allow_destroy => true 
end 

房屋模型

class House < ActiveRecord::Base 
    belongs_to :user 
    belongs-to :type 
end 

型模型

class Type < ActiveRecord::Base 
    has_many :houses 
accepts_nested_attributes_for :houses 
end 

類型的控制器

class TypesController < ApplicationController 
    def new 
    @type = Type.new 
    end 

    def create 
    @type = Type.new(params[:type]) 
    @type.houses = current_user.house 

    if @type.save 
     redirect_to edit_house_path 
     flash[:success] = "yeah" 
    else 
     render :new 
     end 
    end 
end 

型new_view

<div> 
<%= form_for @type, :url => types_path, :method => :post do |t| %> 

<%= t.fields_for :house do |h| %> 
<%= h.label :name %><%= h.text_field :name %> 
<% end %> 

<ul> 
<li>test_1:<%= t.radio_button :kind, "test_1" %></li> 
<li>test_2:<%= t.radio_button :kind, "test_2" %></li> 
<li>test_3:<%= t.radio_button :kind, "test_3" %></li> 
</ul> 
<%= t.submit "create", :class => "blue" %> 
<% end %> 
</div> 
+0

你真正的問題是什麼。請更具體請 – shingara 2012-03-09 10:48:55

+0

問題是:用戶我將創建房屋並在同一時間鍵入,所以每次我嘗試分配兩個軌道吐出這個問題:無法批量分配受保護的屬性:房子和然後當我把類型attr_assible只是房子出現這個新的錯誤:未知的屬性:房子 – dcalixto 2012-03-09 10:54:32

+0

問題是,房子還沒有分配給用戶,這就是我想要做的類型創建控制器! – dcalixto 2012-03-09 11:00:09

回答

2

您需要使用命名關聯關係的field_for所以它

<%= t.fields_for :houses do |h| %> 

,而不是

<%= t.fields_for :house do |h| %> 
+0

我試過這個,但我不知道爲什麼現在的房子text_field消失 – dcalixto 2012-03-09 11:04:19

+0

我認爲,因爲我沒有使用構建方法。 – dcalixto 2012-03-09 11:06:48

+0

是的,如果沒有房屋定義,你看不到它。你需要在你的form_field上看到它之前建立你的關聯對象。它就像與form_for相關聯的對象。你需要建立它。 – shingara 2012-03-09 11:08:26

1

如果你的問題是,嵌套的房子在你的類型對象不存在創建類型時,你需要顯示NEW_TYPE形式之前添加類似以下內容到你的新動作:

@type.houses.build(:user_id => current_user.id) 

這將允許您的fields_for表單元素工作,並且@ type.save函數可以在創建操作中正確創建嵌套資源。

+0

許多感謝的jon,我已經這樣做了,但現在不能將current_user關聯到房屋並鍵入 – dcalixto 2012-03-09 11:36:20

+0

,因爲current_user只是在這個創建中請求一個房屋。 – dcalixto 2012-03-09 11:38:05

+0

當然可以。查看我更新的代碼。 – Jon 2012-03-09 11:43:53