[英]how to get the type and id in polymorphic association
On the page displaying bibliography, I added the possibility to add a comment. 在显示书目的页面上,我添加了添加评论的可能性。
These are my models: 这些是我的模型:
class Biblio < ApplicationRecord
has_many :comments, as: :commentable
and: 和:
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
This is the form for leaving a comment: 这是发表评论的形式:
<%= form_for @biblio.comments.build, url: administration_create_comment_path do |f| %>
<%= f.text_field :texte_comment %>
<%= f.submit %>
The comment controller than contains this: 注释控制器包含以下内容:
def create
@comment = Comment.new(comment_params)
@comment.save
end
def comment_params
params.require(:comment).permit(
:texte_comment
)
end
My question is: how do I get the commentable_type
and commentable_id
that are created in @biblio.comments.build
我的问题是:如何获取在@biblio.comments.build
中创建的commentable_type
和commentable_id
Because when I this in a rails console, it works like a charm: 因为当我在Rails控制台中进行操作时,它就像一种魅力:
b = Biblio.find(115)
b.commentaires.build
=> #<Commentaire id: nil, utilisateur_id: nil, texte_comment: nil, created_at: nil, updated_at: nil, commentable_type: "Biblio", commentable_id: 115>
In other words: what works in the console, how do I get that in my controller? 换句话说:什么在控制台中起作用,如何在控制器中获得它?
You need to send biblio's id on the form submit by adding it as a hidden field in your form: 您需要通过在表单提交中将书夹的ID添加为隐藏字段来发送书夹的ID:
<%= f.hidden_field :commentable_id %>
Now in your controller you can query with the id in params like this: 现在,在您的控制器中,您可以使用以下参数来查询ID:
def create
biblio = Biblio.find_by_id(params[:comment][:commentable_id])
@comment = biblio.commentaires.build(comment_params)
@comment.save
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.