简体   繁体   中英

Rails-Mongoid-Devise: On create, error message “User can't be blank”

Simply, I'm using Mongoid and Devise in a Rails 5.2 application. In the model files, a User has_many :trips and a Trip belongs_to :user . Upon form submission to create a new Trip, the save is failing with the error "User can't be blank". I can fix the problem by setting @trip.user = current_user before the save operation and all looks good in the database and in subsequent queries, but I don't remember having to do this before. It's been a while since I did any real work with Rails (since 1.1, really - yeah, that long), but I don't remember having to do that with an ActiveRecord model. I was thinking that setting the associations in the model was supposed to take care of that. Has there been a major change, or is there something different about Mongoid? I did mess with the params hash (using trip_params.to_h ) before saving because I need to convert a string to an array, but I don't see any indication of a user in the hash even before I change it.

If you are creating a trip on the instance of a user object like

@user = User.find(params[:user_id])

then

@user.create_trip(attributes)

then you need not set user while creating a trip.But if you are creating a trip directly like

Trip.new(attributes)
trip.save!

then you must specify the user while creating trip

No active record takes care if all the associations that are specified for the object are fullfilled or not it doesnt set the associations for us

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM