2012-09-05 28 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| %>