代码之家  ›  专栏  ›  技术社区  ›  Sudeep Ghimiray

在Rails中呈现json时语句无效

  •  -1
  • Sudeep Ghimiray  · 技术社区  · 6 年前

    下面是我用来呈现json的代码片段

    def show
       @product = Product.find(params[:id])
          render json: @product.to_json(:include => { :items => { :only => [:id, 
    :description] }}) 
    end
    

    当呈现json for has many attributes model时,我得到如下无效语句:

    (Mysql2::Error: Unknown column 'items.product_id' in 'where clause': SELECT `items`.* FROM `items` WHERE `items`.`product_id` = 1):
    

    而我有一个名为products\u id的列作为外键,而不是product\u id。我需要将语句作为products\u id抛出,而不更改数据库中的列名。

    1 回复  |  直到 6 年前
        1
  •  1
  •   P. Boro    6 年前

    在你的产品模型中,你应该有 has_many :items product_id . 要更改外键,需要将此行更改为 has_many :items, foreign_key: :products_id .