如何 return json 中包含要使用 JBuilder 关联的模型的值

how to return values in json that contain models to be associated using JBuilder

我想 return json 中包含要使用 JBuilder 关联的模型的值。 但我不知道该怎么做。我遇到了“undefined method xx”的错误 这是我的 rails.

设置

型号

app/models/item.rb

belongs_to :user

app/models/user.rb

include UserImageUploader[:image]
has_many :item

vim app/uploaders/user_image_uploader.rb

# MiniMagick
require 'image_processing/mini_magick'

class UserImageUploader < Shrine
  include ImageProcessing::MiniMagick
  # The determine_mime_type plugin allows you to determine and store the actual MIME type of the file analyzed from file content.
  plugin :determine_mime_type
  plugin :store_dimensions
  plugin :pretty_location
  plugin :processing
  plugin :recache
  #The versions plugin enables your uploader to deal with versions,
  #by allowing you to return a Hash of files when processing.
  plugin :versions

  process(:store) do |io, context|
    original = io.download

    thumbnail = ImageProcessing::MiniMagick
      .source(original)
      .resize_to_limit!(600, nil)

    original.close!

    { original: io, thumbnail: thumbnail }
  end

  #plugin :versions

  #plugin :delete_promoted
  #plugin :delete_raw
end

items_controller.rb

@items = Item.includes(:user).page(params[:page] ||= 1).per(8).order('created_at DESC')
render 'index', formats: 'json', handlers: 'jbuilder'

Item/index.json.jbuilder

json.array! @items do |t|
  json.id t.id  //get the value normally
  json.created_at t.created_at //get the value normally 
  Json.user_id t.user.id  //undefined method `id’ 
  json.user_original_img t.user.image_url(:original) //undefined method `image_url' 
end

如上,我无法获取关联模型的值。

顺便说一句,我可以使用 rails 控制台正确检查值。

捆绑执行 rails c

Item.first.user.image_url(:original)

  Item Load (1.5ms)  SELECT  `items`.* FROM `items` ORDER BY `items`.`id` ASC LIMIT 1
  User Load (0.7ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
=> "https://xx.s3.ap-northeast-1.amazonaws.com/store/user/1/image/original-xx”

Item.first.user.id
   (19.0ms)  SET NAMES utf8mb4,  @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'),  @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
  Item Load (0.9ms)  SELECT  `items`.* FROM `items` ORDER BY `items`.`id` ASC LIMIT 1
  User Load (0.8ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
=> 1

让我知道我错在哪里。

感谢您阅读我的问题。

似乎 @items 列表中的某些项目没有关联的用户,或者它们的 user_id 字段是 nil。那么 item.user 将是 nil。当您执行 nil.image_url 时,您会得到 NoMethodError: undefined method 'image_url' for nil:NilClass .

您可以在迁移中的 ItemUser 之间添加一个外键约束,以避免这样的问题:

add_foreign_key :items, :users

注意:
添加外键仍然允许空值。您还必须在迁移文件中添加以下内容,以避免 user_id 列中出现空值:

change_column_null :items, :user_id, false

感谢@3limin4t0r 指出这一点。

app/models/user.rb

include UserImageUploader[:image]
has_many :item

应该是 has_many :items,对此不是很有信心,但这可能是您在数据库中发现空白列的原因。 has_many, belongs_to 关系应默认为必需。