Search code examples
ruby-on-railsmongodbmodelruby-on-rails-5

Rails Mongodb can't save record


I'm using Mongodb in my Rails app. I have 2 models, which are Account and User. Account has many users and users belongs to account.

Account model

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

User model

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 controller

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

I can successfully sign up an account with a user. But when I tried to add a new user, the user record can't be saved. I assigned a password for users when creating a new user.

The error messages:

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.

If I removed the self.create_with_password and manually type in the password in the form, it works. So i guess the error must be in the self create password, it seems like doesn't save the record. By the way I'm using Rails 5.0. Any idea to solve this?


Solution

  • Hey @ternggio Welcome to community.

    Account can't be blank.

    This error appear due to belongs_to statement in user.rb.

    In rails > 5 belongs_to is by default required, You can set as optional with marking optional: true.

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

    and remove below line.

    validates :account, :presence => false
    

    Hope, this will help you.