【问题标题】:Rails Mongodb can't save recordRails Mongodb 无法保存记录
【发布时间】:2020-05-22 02:21:15
【问题描述】:

我在我的 Rails 应用程序中使用 Mongodb。我有 2 个模型,分别是 AccountUser。帐号有很多用户,用户属于帐号。

Account型号

has_many :users, :inverse_of => :account, :dependent => :destroy
validates :organization_name, presence: true, uniqueness: true

User型号

belongs_to :account, :inverse_of => :users
validates :account, :presence => false
validates :email, presence: true
has_secure_password
validates :password, length: { minimum: 6 }, allow_nil: true

def User.new_token
 SecureRandom.urlsafe_base64
end

def self.create_with_password(attr={})
 generated_password = attr[:email] + User.new_token
 self.create!(attr.merge(password: generated_password, password_confirmation: generated_password))
end

User控制器

def new
    @user = User.find_by(params[:id])
    @user = @current_user.account.users.new
end

def create
    @user = User.find_by(params[:id])
    @user = @current_user.account.users.create_with_password(user_params)
    respond_to do |format|
if @user.save
  format.html { redirect_to @user, notice: 'User was successfully created.' }
    format.json { render :show, status: :created, location: @user }
    format.js
else
  format.html { render 'new' }
    format.json { render json: @user.errors, status: :unprocessable_entity }
    format.js { render json: @user.errors, status: :unprocessable_entity }
end
end
end

private
    def user_params
      params.require(:user).permit(:id, :email, :password, :password_confirmation, :owner, :admin)
    end

我可以成功注册一个用户的帐户。但是当我尝试添加新用户时,无法保存用户记录。我在创建新用户时为用户分配了密码。

错误信息:

message: Validation of User failed. summary: The following errors were found: Account can't be blank resolution: Try persisting the document with valid data or remove the validations.

如果我删除了 self.create_with_password 并在表单中手动输入密码,它就可以工作。所以我猜错误一定是在自我创建密码中,似乎没有保存记录。顺便说一句,我使用的是 Rails 5.0。有什么办法解决这个问题吗?

【问题讨论】:

    标签: ruby-on-rails mongodb model ruby-on-rails-5


    【解决方案1】:

    嘿@ternggio 欢迎来到社区。​​p>

    帐号不能为空。

    由于user.rb 中的belongs_to 语句而出现此错误。

    在 rails > 5 belongs_to 是默认需要的,您可以设置为可选并标记optional: true

    belongs_to :account, :inverse_of => :users, optional: true
    

    并删除下面的行。

    validates :account, :presence => false
    

    希望,这会对您有所帮助。

    【讨论】:

    • 如果我在此行下方删除validates :account, :presence => false,则用户记录已成功保存,但带有account_id = nil。帐户和用户之间没有关联。
    • 以上行无论如何都没用。但是由于其他原因, account_id 为零。确保帐户在创建帐户时存在。
    • 我能够通过将@user.account_id = @current_user.account.id 添加到User 控制器中的create 操作来解决问题,因为在用户表中有一个account_id 属性。然后我按照您的解决方案删除了​​这一行validates :account, :presence => false,一切正常。我想给你一个赞成票,但我没有足够的声誉。谢谢。
    • 不用担心,我很高兴该解决方案对您有用。祝你有美好的一天。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多