首页 \ 问答 \ Rails 4 - 多态关联 - 多个关联(Rails 4 - Polymorphic associations - multiple associations)

Rails 4 - 多态关联 - 多个关联(Rails 4 - Polymorphic associations - multiple associations)

我正在尝试制作Rails 4应用程序。

我有一个多态的评论模型。 我也有用户,个人资料和文章的模型。

协会是:

article.rb

belongs_to :user
has_many :comments, as: :commentable
accepts_nested_attributes_for :comments

comments.rb

belongs_to :user
belongs_to :commentable, :polymorphic => true

profile.rb

belongs_to :user
has_many :addresses, as: :addressable

user.rb

has_many :articles
has_many :comments
has_one :profile

我很难理解这在实践中是如何运作的。

当我使用我的控制台创建注释时,如下所示:

Comment.create(可评论:Article.first,user_id:“1”,意见:“test”)文章加载(15.5ms)SELECT“articles”。* FROM“articles”ORDER BY“articles”。“created_at”DESC LIMIT 1 (0.2ms)BEGIN SQL(6.3ms)INSERT INTO“comments”(“commentable_id”,“commentable_type”,“user_id”,“views”,“created_at”,“updated_at”)VALUES($ 1,$ 2,$ 3,$ 4, $ 5,$ 6)RETURNING“id”[[“commentable_id”,3],[“commentable_type”,“Article”],[“user_id”,1],[“opinion”,“test”],[“created_at”, “2016-01-01 01:51:20.711415”],[“updated_at”,“2016-01-01 01:51:20.711415”]](1.3ms)COMMIT =>#

这样可行。

但是,当我转到视图并尝试使用表单创建新注释时,我得到:

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:30s):

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替换开头行中的@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 Half Face的解决方案适用于评论表单,但现在唯一不起作用的部分是获取撰写文章的用户的名称以显示在页面上。

在我的文章展示页面中,我有:

<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容器。


I am trying to make a Rails 4 app.

I have a comments model which is polymorphic. I also have models for user, profile and article.

The associations are:

article.rb

belongs_to :user
has_many :comments, as: :commentable
accepts_nested_attributes_for :comments

comments.rb

belongs_to :user
belongs_to :commentable, :polymorphic => true

profile.rb

belongs_to :user
has_many :addresses, as: :addressable

user.rb

has_many :articles
has_many :comments
has_one :profile

I'm struggling to understand how this works in practice.

When I use my console to create a comment as follows:

Comment.create(commentable: Article.first, user_id: "1", opinion: "test") Article Load (15.5ms) SELECT "articles".* FROM "articles" ORDER BY "articles"."created_at" DESC LIMIT 1 (0.2ms) BEGIN SQL (6.3ms) INSERT INTO "comments" ("commentable_id", "commentable_type", "user_id", "opinion", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["commentable_id", 3], ["commentable_type", "Article"], ["user_id", 1], ["opinion", "test"], ["created_at", "2016-01-01 01:51:20.711415"], ["updated_at", "2016-01-01 01:51:20.711415"]] (1.3ms) COMMIT => #

That works.

However, when I go to the view and try to create a new comment using the form, I get:

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"

Nothing happens.

Further, I tried following the example in this video tutorial (around 7m:30s):

https://gorails.com/episodes/comments-with-polymorphic-associations?autoplay=1

I changed my comments partial, which was working to display comments created in the console (but not in the view form) from:

<% @article.comments.each do | comment | %>
  <div class="well">
    <%= comment.opinion %>
    <div class="commentattribution">
      <%= comment.user.formal_name_and_title %>
    </div>
  </div>
<% end %>

to add a local variable in my articles show page where I render the comments partial:

<%= render 'comments/display', locals: {commentable: @article} %>

and replace @article in the opening line with @commentable:

<% @commentable.comments.each do | comment | %>
  <div class="well">
    <%= comment.opinion %>
    <div class="commentattribution">
      <%= comment.user.formal_name_and_title %>
    </div>
  </div>
<% end %>

Now, when I save that and try to render the article show page, I get this error:

undefined method `comments' for nil:NilClass

I don't understand what this error message means, but it was all working fine until I tried to reference commendable instead of article. The specific line item referenced in the error message is:

<% @commentable.comments.each do | comment | %>

Can anyone see what's going wrong here?

When I try:

<% commentable.comments.each do | comment | %>

I get this error:

undefined local variable or method `commentable' for #<#<Class:0x007fd13b93dac8>:0x007fd134530270>

I have read some other posts where people have had trouble with polymorphic associations belonging to more than one resource. For example, my comments belong to users as well as articles. I've not been able to follow the resolution or properly grasp the issue with that arrangement.

Joe Half Face's solution worked for the comments form, but the only part that isn't working now is getting the name of the user that wrote the article to appear on the page.

In my articles show page, I have:

<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>

The title, shows and date created shows, but neither of the user attributes appear.

It's just a blank div container showing in the code inspector.


原文:https://stackoverflow.com/questions/34553319
更新时间:2022-03-25 15:03

最满意答案

之所以发生这种情况,是因为没有为index.html提供服务的用户在他们直接访问这些网址时引导您的应用。

为了激增,您可以添加一个200.html文件 ,其中包含与您正在部署的index.html相同的内容(或者只是将其重命名为200.html ) - 然后这将在他们访问的任何URL上提供给用户不对应静态文件,允许您的应用程序开始运行。


编辑:看起来你正在使用create-react-app 。 这在您在本地开发时有效,因为create-react-appreact-scripts包处理为index.html提供服务作为这些请求的后备。

react-scripts用户指南中有关于如何在部署到GitHub Pagessurge.sh 时处理此问题的部分(如上所述)。


This is happening because users aren't being served the index.html which bootstraps your app when they visit those URLs directly.

For surge, you can add a 200.html file which contains the same contents as the index.html you're deploying (or just rename it to 200.html) - this will then be served to users at any URL they visit which doesn't correspond to a static file, allowing your app to start running.


Edit: looks like you're using create-react-app. This works when you're developing locally because create-react-app's react-scripts package handles serving your index.html as a fallback for these requests.

The react-scripts user guide has sections on how to handle this when deploying to GitHub Pages and surge.sh (as above).

相关问答

更多
  • 使用活动的类名称 如果你想使用this.props.history,那么你必须设置历史记录 // create browser history for navigating import createBrowserHistory from 'history/lib/createBrowserHistory'; let history = createBrowserHistory(); 然后将历史道具添加到路由器
  • 看看对这个问题的接受答案和一般性质的评论(“不工作”),我认为这可能是对这里涉及的问题的一般性解释的好地方。 所以这个答案是作为OP的具体用例的背景信息/阐述。 请多多包涵。 服务器端vs客户端 了解这一点的第一件大事是,现在有2个地方解释了URL,而在过去曾经只有1个。 过去,当生活很简单时,一些用户向服务器发送了一个请求http://example.com/about ,该服务器检查了URL的路径部分,确定用户正在请求关于页面,然后发回页。 使用客户端路由,这是React-Router提供的,事情并不简 ...
  • 您可以使用router.push()而不是使用历史记录。 为此,您可以使用上下文或withRouter HoC ,这比直接使用上下文更好: import { withRouter } from 'react-router'; class Logout extends React.Component { handleLogoutClick() { console.info('Logging off...'); auth.logout(this.doRedirect() ...
  • 如果激增很高(我相信>= 2.0 )优步使用这种确认方案。 否则,不显示此数字页面。 根据我目前的理解,使用优步API不可能影响这一点。 If the surge is high (i believe >= 2.0) Uber uses this scheme of confirmation. Otherwise, this numeric page is not shown. There is no possibility to affect this using Uber API, in my curr ...
  • 您应该将Navigation组件呈现为您的App组件的一部分,而不是在您的index.js App应该看起来像 class App extends Component { render() { return (
    {this.props.children}
    ); } } 你的路线也需要改变一点。
  • @Rob M.你是我的英雄! 谢谢! 这正是重点。 当我将react-router的版本更改为2.8时。 如你所说,它工作得很好。 如果我正确理解了文档,建议使用react-router-dom代替更高级别的路由器 我得到了这个正确的? @Rob M. you are my hero! Thank you! That was exactly the point ...
  • 在Swift中,名称subscript不像一个普通函数(实际上你可以看到它没有用func关键字声明)。 相反,带有subscript成员的struct / enum /类可以与括号语法一起使用。 也就是说,你的代码应该看起来像这样: //create arbitrary matrix, this works fine var matrix : Matrix = Matrix([[4,7], [2,6]]) // I want to get the 4 but this do ...
  • createRoutes需要一个routes对象,但是你传递的是一个history实例。 您需要以允许您在服务器上导入它们的方式从routes功能中提取 。 // routes.js export const routes = (
  • 之所以发生这种情况,是因为没有为index.html提供服务的用户在他们直接访问这些网址时引导您的应用。 为了激增,您可以添加一个200.html文件 ,其中包含与您正在部署的index.html相同的内容(或者只是将其重命名为200.html ) - 然后这将在他们访问的任何URL上提供给用户不对应静态文件,允许您的应用程序开始运行。 编辑:看起来你正在使用create-react-app 。 这在您在本地开发时有效,因为create-react-app的react-scripts包处理为index.ht ...
  • 代码中的browserHistory可能需要一个basename。 看看类似问题的答案是否适合您: https : //stackoverflow.com/a/36765496/4772334 The browserHistory in your code may need a basename. See if a similar question's answer works for you: https://stackoverflow.com/a/36765496/4772334

相关文章

更多

最新问答

更多
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何使用自由职业者帐户登录我的php网站?(How can I login into my php website using freelancer account? [closed])
  • SQL Server 2014版本支持的最大数据库数(Maximum number of databases supported by SQL Server 2014 editions)
  • 我如何获得DynamicJasper 3.1.2(或更高版本)的Maven仓库?(How do I get the maven repository for DynamicJasper 3.1.2 (or higher)?)
  • 以编程方式创建UITableView(Creating a UITableView Programmatically)
  • 如何打破按钮上的生命周期循环(How to break do-while loop on button)
  • C#使用EF访问MVC上的部分类的自定义属性(C# access custom attributes of a partial class on MVC with EF)
  • 如何获得facebook app的publish_stream权限?(How to get publish_stream permissions for facebook app?)
  • 如何防止调用冗余函数的postgres视图(how to prevent postgres views calling redundant functions)
  • Sql Server在欧洲获取当前日期时间(Sql Server get current date time in Europe)
  • 设置kotlin扩展名(Setting a kotlin extension)
  • 如何并排放置两个元件?(How to position two elements side by side?)
  • 如何在vim中启用python3?(How to enable python3 in vim?)
  • 在MySQL和/或多列中使用多个表用于Rails应用程序(Using multiple tables in MySQL and/or multiple columns for a Rails application)
  • 如何隐藏谷歌地图上的登录按钮?(How to hide the Sign in button from Google maps?)
  • Mysql左连接旋转90°表(Mysql Left join rotate 90° table)
  • dedecms如何安装?
  • 在哪儿学计算机最好?
  • 学php哪个的书 最好,本人菜鸟
  • 触摸时不要突出显示表格视图行(Do not highlight table view row when touched)
  • 如何覆盖错误堆栈getter(How to override Error stack getter)
  • 带有ImageMagick和许多图像的GIF动画(GIF animation with ImageMagick and many images)
  • USSD INTERFACE - > java web应用程序通信(USSD INTERFACE -> java web app communication)
  • 电脑高中毕业学习去哪里培训
  • 正则表达式验证SMTP响应(Regex to validate SMTP Responses)