我正在尝试制作一个Rails 4应用程序。
我有一个注释模型,它是多态的。我也有模型的用户,配置文件和文章。
这些协会是:
article.rb
belongs_to :user
has_many :comments, as: :commentable
accepts_nested_attributes_for :commentscomments.rb
belongs_to :user
belongs_to :commentable, :polymorphic => trueprofile.rb
belongs_to :user
has_many :addresses, as: :addressableuser.rb
has_many :articles
has_many :comments
has_one :profile我很难理解这在实践中是如何运作的。
当我使用我的控制台创建注释时,如下所示:
Comment.create(注释: Article.first,user_id:"1",意见:“测试”)文章负载(15.5ms)从“文章”的顺序中选择“文章”.*。"created_at“DESC限制1 (0.2ms)开始在”注释“("commentable_id”、"commentable_type“、"user_id”、“意见”、“created_at”、"updated_at")中插入.*值($1,$2,$3,$4,$5,$6)返回"id“at", "2016-01-01 01:51:20.711415"]提交=> #
这是可行的。
但是,当我转到视图并尝试使用该表单创建一个新的注释时,我得到:
SELECT "articles".* FROM "articles" WHERE "articles"."id" = $1 ORDER BY "articles"."created_at" DESC LIMIT 1 [["id", 3]]
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Unpermitted parameter: comment
(0.2ms) BEGIN
(0.1ms) COMMIT
[ActiveJob] Enqueued Searchkick::ReindexV2Job (Job ID: 4fd1ceb5-7882-4381-a2df-5913082af621) to Inline(searchkick) with arguments: "Article", "3"什么都没发生。
此外,我尝试遵循本视频教程中的示例(大约7m:30):
https://gorails.com/episodes/comments-with-polymorphic-associations?autoplay=1
我更改了注释部分,该部分用于显示在控制台中创建的注释(但不是在视图表单中创建的),原因是:
<% @article.comments.each do | comment | %>
<div class="well">
<%= comment.opinion %>
<div class="commentattribution">
<%= comment.user.formal_name_and_title %>
</div>
</div>
<% end %>若要在文章显示页面中添加局部变量,请将注释显示为部分:
<%= render 'comments/display', locals: {commentable: @article} %>并将开头行中的“文章”改为“评论性”:
<% @commentable.comments.each do | comment | %>
<div class="well">
<%= comment.opinion %>
<div class="commentattribution">
<%= comment.user.formal_name_and_title %>
</div>
</div>
<% end %>现在,当我保存它并尝试呈现文章显示页面时,我得到了以下错误:
undefined method `comments' for nil:NilClass我不明白这条错误信息意味着什么,但直到我试图引用值得称赞的文章而不是文章之前,它一直运作良好。错误消息中引用的特定行项是:
<% @commentable.comments.each do | comment | %>有人能看到这里出了什么问题吗?
当我尝试:
<% commentable.comments.each do | comment | %>我知道这个错误:
undefined local variable or method `commentable' for #<#<Class:0x007fd13b93dac8>:0x007fd134530270>我读过一些其他的帖子,其中人们对属于多个资源的多态关联有困难。例如,我的评论既属于用户,也属于文章。我没有能够遵循决议,也没有正确地理解这个安排的问题。
Joe的解决方案对评论表单起了作用,但现在唯一不起作用的部分是让写文章的用户的名字出现在页面上。
在我的文章展示页中,我有:
<div class="articletitle">
<%= @article.title %>
</div>
<div class="commentattributionname">
<%= @article.user.try(:formal_name) %>
</div>
<div class="commentattributiontitle">
<%= @article.user.try(:formal_title) %>
</div>
<div class="commentattributiondate">
<%= @article.created_at.try(:strftime, '%e %B %Y') %>
</div>标题、显示和创建日期显示,但这两个用户属性都没有出现。
它只是一个显示在代码检查器中的空白div容器。
发布于 2016-01-01 05:17:39
1)如果将变量传递给分部,则它是局部的,而不是实例:
<%= render :partial => 'comments/display', locals: {commentable: @article} %>2)还注意到控制器渲染和视图渲染是不同的。在控制器中,您不必指定:partial=>,因为Rails中的控制器应该呈现整个模板,但是如果您在视图文件中,那么Rails在每个请求中只能呈现一个模板
https://stackoverflow.com/questions/34553319
复制相似问题