【问题标题】:association named not found perhaps misspelled issue in rails association在 Rails 协会中未找到名为的协会可能拼写错误的问题
【发布时间】:2013-10-07 18:07:22
【问题描述】:

这是我的控制器

@post = Post.joins(:customers).select("customers.*,posts.*").find params[:id]

我的帖子模型

belongs_to :customer

我的客户模型

has_many :posts

我得到了错误

Association named 'customers' was not found on Post; perhaps you misspelled it?

这是我的控制器输出:

Processing by PostsController#show as */*
  Parameters: {"id"=>"6"}
  Post Load (0.5ms)  SELECT "posts".* FROM "posts" WHERE "posts"."id" = $1 LIMIT 1  [["id", "6"]]
Completed 500 Internal Server Error in 113ms

ActiveRecord::ConfigurationError (Association named 'customers' was not found on Post; perhaps you misspelled it?):
  app/controllers/posts_controller.rb:16:in `show'

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    这是一个典型的拼写错误:

    @post = Post.joins(:customers).select("customers.*,posts.*").find params[:id]
    # should be:
    @post = Post.joins(:customer).select("customers.*,posts.*").find params[:id]
                              #^^ no plural
    

    因为你定义了这样的关系(使用单数):

    # Post model
    belongs_to :customer
    

    需要知道的一些事情:

    • 在joins/includes 方法中,始终使用与关系完全相同的名称
    • 在where子句中,始终使用关系的复数名称(实际上是表的名称,默认为复数的模型名称,但也可以手动设置)

    例子:

    # Consider these relations:
    User has_many :posts
    Post belongs_to :user
    
    # Usage of joins/includes & where:
    User.includes(:posts).where(posts: { name: 'BlogPost #1' })
                      #^            ^
    Post.joins(:user).where(users: { name: 'Little Boby Table' })
                  #^^           ^
    

    类似问题:

    【讨论】:

    • 好的,现在我需要进一步澄清。我在两张桌子上都有created_at。我需要两个日期(即)Registration Date 和 Post Date 我怎样才能得到它。
    • 这是另一个与此无关的问题,如果需要,请在 Stackoverflow 上创建另一个问题。 (但通常你使用post.created_at 来获取 Post 实例的 created_at 值)
    • 为什么Rails不能在所有情况下默认不复数?不再有复数错误..
    • 哇,这个解释很有道理。谢谢。
    • 一些知识救命!
    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多