こんにちは!現在、Railsでタグ機能を実装しようとしています。
テーブルの関係はToxi法で、Tag_mapを通して、ArticleとTagを関連づけています。
参考までに関係を記載します。
ArticleModel
class Article < ApplicationRecord has_many :tag_maps, dependent: :destroy has_many :tags, through: :tag_maps def save_tags(tags) current_tags = self.tags.pluck(:name) unless self.tags.nil? old_tags = current_tags - tags new_tags = tags - current_tags old_tags.each do |old_name| self.tags.delete Tag.find_by(name: old_name) end new_tags.each do |new_name| article_tag = Tag.find_or_create_by(name: new_name) self.tags << article_tag end end end
Tag_mapModel
class Tag < ApplicationRecord has_many :tag_maps, dependent: :destroy has_many :articles, through: :tag_maps end
TagModel
class TagMap < ApplicationRecord belongs_to :article belongs_to :tag end
フォームから、タグの情報を:tag_listに乗せて,article_contorllerのcreateアクションに渡そうとしていますが....
_form.html.erb
<%= form_with model: article, local: true do |f| %> --省略-- <div class="form-group"> <%= f.label 'タグ' %> <%= f.text_field :tag_list %> </div> <%= f.submit %>
articles_controller.rb
def create @article = current_user.articles.build(article_params) tag_list = params[:tag_list].split(",") if @article.save @article.save_tags(tag_list) redirect_to @article, notice: "作成完了しました" else render :new, alert: "作成できませんでした" end end
フォームから登録をすると、
undefined method `split' for nil:NilClass
と出ました。
これはparams[:tag_list]がnilになっているからだと思うのですが、どう記述すれば上手く登録できるのかわからず、行き詰ってしまいました。
問題箇所と解決策がわかる方、ご教授よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー