How can I check if the model is saved when using the Ruby .map method? My code is as follows:
@subscription = feed.map { |subscribe| Subscription.create(dashboard_id: dashboard, category_id: category, feed_id: subscribe) }
respond_to do |format|
if @subscription.save
format.html { redirect_to subscriptions_path, notice: 'Subscription was successfully created.' }
format.json { render action: 'show', status: :created, location: @subscription }
else
format.html { render action: 'new' }
format.json { render json: @subscription.errors, status: :unprocessable_entity }
end
The line if @subscription.save
throws an error undefined method
save' for #`.
I understand why this is, but how do I fix this? I still want to check for save before redirecting.
Thanks.
map
returns an array, so @subscription
would be an array of Subscription
objects, since you're using create
.
You could do something like:
@subscription.any?(&:blank?)
to see if there are any nil
, false
, or ""
elements in the array...
Or (worse, because it would be another database call for each record), you could do:
@subscription.map(&:save).flatten.any?(&:blank)
to re-save all elements in the array and ensure all returned true
.
I think the former is the best approach... So your code would look like:
respond_to do |format|
unless @subscription.any?(&:blank?)
format.html { redirect_to subscriptions_path, notice: 'Subscription was successfully created.' }
format.json { render action: 'show', status: :created }
else
format.html { render action: 'new' }
format.json { render json: @subscription.map(&:errors).flatten, status: :unprocessable_entity }
end
end
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.