association named not found perhaps misspelled issue in rails association

后端 未结 1 647
萌比男神i
萌比男神i 2020-12-01 07:36

Here is my controller

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

My post model

belongs         


        
相关标签:
1条回答
  • 2020-12-01 07:55

    This is a typical typo error:

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

    Because you defined the relation like this (using singular):

    # Post model
    belongs_to :customer
    

    Some stuff to know:

    • In the joins/includes method, always use the exact same name as the relation
    • In the where clauses, always use the pluralized name of the relation (actually, the table's name, which is by default the model name in plural but can also be manually set)

    Examples:

    # 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' })
                  #^^           ^
    

    Similar questions:

    • How to query a model based on attribute of another model which belongs to the first model?
    • Rails active record querying association with 'exists'
    • Rails 3, has_one / has_many with lambda condition
    • Rails 4 scope to find parents with no children
    0 讨论(0)
提交回复
热议问题