I am currently making my own tag function on Ruby On Rails.
This is probably a typical implementation of the Article and Tag models and the intermediate models.
has_many:article_tags, dependent::destroy
has_many:tags, through:article_tags
I would like to save both the article and the tag at the same time. When saving the article, it is stuck in the controller's process.
[email protected] ve&@article.save_tags(tags_list)
flash[:success] = "Created article"
redirect_to articles_url
else
render 'articles/new'
end
Within the save_tags
method, perform validation (for example, limit the number of characters, etc.), and
Added errors in error.add
.I try to return false
for errors.
Here's how to add an error message:
errors.add(:tag_list,"The number of tags is over.") if tags.count > 5
At this time (of course) the article model is validated first, followed by the tag check.
In other words, if you do not clear the validation of the Article model first, you will not see the tag error message (if you clear the validation of the Article model, you will see the Tag error message).
For example, if the title of the article is missing and more than seven tags are registered, the error message is
·The title of the article is empty.
will only be displayed, and the tag validation results will not be displayed.
I'd like to ask for it.
·The title of the article is empty.
·The number of tags is over.
I would like to print at the same time.
How do we achieve this?
It seems to be a relatively common form, but I am too amateur to know how to search.
I would appreciate it if you could let me know.
Thank you for your cooperation.
The comments seem to have already been resolved, but I will summarize them in my answer.
The problem this time is that when the first record save @article.save
failed, @article.save&&@article.save_tags(tag_list)
in the latter half of save_tags
would not have been added to the error.
The ruby handles the &
, ||
operators with a short circuit during their evaluation.If the return value of the expression is determined at the time of the first argument of this binomial operator, the second argument is not evaluated.
For example, the following are no errors:
true||raise
false & raise
Now, in this case, the requirement is that the short circuit is in the way and that we just want to do both and the result.
In ruby, &
and |
are available to achieve this.In fact, they are defined as just the TrueClass
, FalseClass
, so just like the regular binomial operator,
Run in the order shown in .
there is no short-circuit evaluation in this case.
— ri'FalseClass#&'
579 Understanding How to Configure Google API Key
626 Uncaught (inpromise) Error on Electron: An object could not be cloned
585 PHP ssh2_scp_send fails to send files as intended
618 GDB gets version error when attempting to debug with the Presense SDK (IDE)
574 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.