投稿記事にタグ付けをするため、1つのフォーム送信で複数のモデルを更新できるというFormオブジェクトを使用しました。
app/models/posts_tag.rb
class PostsTag
include ActiveModel::Model
attr_accessor :title,:text,:answer,:user_id,:image, :name
with_options presence: true do
validates :title
validates :text
validates :name
end
def save
post = Post.create(title: title,text: text,answer: answer,user_id: user_id,image: image)
tag = Tag.where(name: name).first_or_initialize
tag.save
PostTagRelation.create(post_id: post.id, tag_id: tag.id)
end
end
そして投稿時にエラーが発生した際に日本語でエラーメッセージが表示されるようにja.ymlを作成したのですが、英語から日本語に変換してくれませんでした。><
↓はダメだった書き方です。
config/locales/ja.yml
ja:
activerecord:
attributes:
user:
nickname: ニックネーム
post:
title: 投稿タイトル
text: 投稿内容
image: 画像
name: タグ名
そこから下記のように修正したところ日本語に変換してくれました!
config/locales/ja.yml
ja:
activerecord:
attributes:
user:
nickname: ニックネーム
activemodel:
attributes:
posts_tag:
title: 投稿タイトル
text: 投稿内容
image: 画像
name: タグ名
activerecordとactivemodelの違いも分かっていないプログラミング初学者ですが、
とても良い経験となりました。
おわり