Rails: 覚書: 名前空間ありのhas_manyとbelongs_to
Ruby 2.7.2
Rails 6.1.3
rails new try_namespace_association -MCJT \
--skip-action-mailbox \
--skip-action-text \
--skip-active-job \
--skip-active-storage \
--skip-jbuilder && \
cd try_namespace_association && tmux
bin/rails g scaffold account/post title body:text
bin/rails g scaffold account/comment note account_post:belongs_to
bin/rails db:migrate
class Account::Post < ApplicationRecord
has_many :account_comments, class_name: 'Account::Comment', foreign_key: 'account_post_id'
end
class Account::Comment < ApplicationRecord
belongs_to :account_post, class_name: 'Account::Post'
end
open http://localhost:3000/account/posts
open http://localhost:3000/account/comments
bin/rails c -s
p = Account::Post.create!(title: 't1', body: 'b1')
c = Account::Comment.create!(account_post: p, note: 'n1')
c.account_post.title # => "t1"
p.account_comments.count # => 1
p.account_comments.first.note # => "n1"
exit
付録
この記事が気に入ったらサポートをしてみませんか?