添加嵌套属性以设计用户模型

乍一看,这个问题似乎已经得到了回答,但不是我的情况(大部分都与质量分配问题和/或mongoid有关。)即使这里有很多有些相关的问题,我还是找不到答案。 。

所以基本上我在ruby on rails应用程序上使用devise gem进行用户身份validation,我想在用户模型中添加嵌套地址模型。 我也使用simple_form来生成表单视图。

我有一个用户模型:

class User  true end 

这是地址模型:

 class Address < ActiveRecord::Base belongs_to :country belongs_to :state belongs_to :user attr_accessible :street1, :street2, :country_id, :state_id, :city, :postalCode end 

这是用户控制器,我为了添加show动作来显示用户配置文件而进行了覆盖。

 class Users::RegistrationsController  after_sign_up_path_for(resource) else set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format? expire_session_data_after_sign_in! respond_with resource, :location => after_inactive_sign_up_path_for(resource) end else clean_up_passwords resource respond_with resource end end def show @user = User.find(params[:id]) #Add to view count if not viewing own user profile if @user != current_user @user.views += 1 @user.save end @vehicles = Vehicle.where(:user_id => @user) respond_to do |format| format.html # show.html.erb format.json { render json: @user } end end end 

这是创建新用户的视图:

  resource_name, :url => registration_path(resource_name) ) do |f| %> 
false, :autofocus => true, placeholder: 'Pick a username' %> false, placeholder: 'Your email' %> false, placeholder: 'Create a password' %> false, placeholder: 'Confirm your password' %> :check_boxes, :label => "", :required => false %> 'btn btn-success btn-large' %>

因此,创建新用户时的错误是:地址用户不能为空

基本上没有为地址设置外键user_id。

我希望有人能对这个问题有所了解。

我能够在我的应用程序中解决这个问题,但我使用的是强参数。 但是,解决方案仍应适用于您的情况。

而不是覆盖RegistrationsController中的所有方法,我只是覆盖build_resource以传递所需的正确参数。

 def build_resource(params) super(resource_params) end def resource_params params.require(:user).permit(:email, :password, tickets_attributes: [ :description ] ) end 

我的UserTicket模型上也有inverse_of ,如下所示:

 user.rb has_many :tickets, inverse_of: :user ticket.rb belongs_to :user, inverse_of :tickets 

忘记添加user_id以进行地址迁移。 在将belongs_to:user添加到地址模型时,Rails期望它。