2012-09-05 32 views
0

我在Rails 3中有兩個模型 - 一個用戶模型和一個Profile模型。Rails scoped form not assigneding belongs_to

class User < ActiveRecord::Base 
    has_one :profile, :dependent => :destroy 
end 

class Profile < ActiveRecord::Base 
    belongs_to :user 
end 

他們在我的routes.rb文件範圍的,因爲這樣的:

resources :users do 
    resources :profiles 
end 

所以,現在,我的表單創建一個配置文件讀取這樣的(使用SimpleForm):

<%= simple_form_for([@user, @profile]) do |f| %> 
    <%= f.error_notification %> 
    ...(Other Inputs) 
<% end %> 

但是,我認爲用戶標識似乎不會自動發送到配置文件模型。我必須通過控制器手動設置嗎?或者我錯過了什麼?

+0

有記錄在配置文件數據庫字段'user_id'? – thoferon

回答

0

您應該首先確保User和Profile之間的關係確實正常。實際上,你已經把「HAS_ONE:用戶」您的用戶模型中,當我想你的意思是:

class User < ActiveRecord::Base 
    has_one :profile, :dependent => :destroy 
end 

爲了與形式發送用戶ID,形式應該是一個頁面上的URL類似於「localhost:3000/users/5/profiles/new」,您可以使用助手「new_user_profile_path(5)」鏈接到一個ID爲5的用戶。

當您提交表單時,您的ProfilesController中的創建操作。以下應導致創建配置文件的:

def create 
    @user = User.find(params[:user_id]) 
    @profile = @user.build_profile(params[:profile]) 
    @profile.save! 
end 
+0

謝謝!我錯過了行: '@profile = @ user.build_profile(PARAMS [:資料])' 相反,我剛剛被使用: '@profile = Profile.new(PARAMS [:資料]) ' – Bryce

0

加:方法=>:自烏拉圭回合的HTML信息發佈到您的形式是GET應爲POST

simple_form_for([@user, @profile], :method => :post) do |f| %>