Post, Page 등과 같은 다른 모델 및 has_one (또는 belongs_to?) 사용자 모델에 속하는 Comment 모델이 있습니다. 하지만 사용자도 주석을 달 수 있어야하므로 사용자는 다른 사용자로부터 많은 주석을 가져야하며 (이것은 다형성 : 주석을 달 수있는 연관성입니다) 자신이 작성한 자신의 주석을 가져야합니다. 이와 같은 연결을 만드는 가장 좋은 방법은 무엇입니까? User가 Comments와 두 개의 다른 연관을 가지고 있다면 컨트롤러에서 어떻게 Comments for User를 읽고 생성 할 수 있습니까? 이제 나는 이것을하고 그것이 옳지 않다고 생각합니다.
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :comments, as: :commentable
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
belongs_to :user
end
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :content
t.references :commentable, polymorphic: true, index: true
t.belongs_to :user
t.timestamps null: false
end
end
end
해당 연결에 다른 이름을 사용하는 것이 좋습니다.
has_many :comments, as: :commentable
has_many :commented_on, class_name: 'Comment' # you might also need foreign_key: 'from_user_id'.
은 foreign_key
귀하의 경우에는 필요하지 않을한다,하지만 난 그냥 케이스 ™ 그것을 지적하고있다. Rails는 기본적으로 "{class_lowercase} _id"를 추측합니다 (따라서 user_id
User라는 클래스에서).
그런 다음 두 연결 모두에 액세스 할 수 있습니다 ( class_name
Rails가 Comment
에서 찾을 수 없기 때문에 명시 적으로 필요합니다 commented_on
).
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다