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

时间:2019-03-25 11:48:44

标签: ruby-on-rails ruby jbuilder

我想在json中返回包含要使用JBuilder关联的模型的值。 但是我不知道该怎么做。我遇到了“未定义方法xx”的错误 这是我的扶手。

模型

app / models / item.rb

CREATE EXTERNAL TABLE my_db.my_es_ext_table (
   id string,
   text string,
   my_array array<string>,
   created_ts timestamp,
   year int,
   month int
)
STORED BY 'org.elasticsearch.hadoop.hive.EsStorageHandler'
TBLPROPERTIES(
   'es.nodes' = 'aws-host-to-es.us-east-1.es.amazonaws.com', 
   'es.port' = '443' , 
   'es.resource' = 'my_jobs/myjob' , 
   'es.mapping.id' = 'id',
   'es.write.operation' = 'upsert',
   'es.nodes.wan.only' = 'true'
);

app / models / user.rb

$ ssh-keygen -t rsa -b 4096 -C your_email@example.com

vim app / uploaders / user_image_uploader.rb

belongs_to :user

items_controller.rb

include UserImageUploader[:image]
has_many :item

Item / index.json.jbuilder

# 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

如上所述,我无法获得所关联模型的值。

顺便说一句,我可以使用rails console正确检查该值。

捆绑执行轨c

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

让我知道我错了什么地方。

感谢您阅读我的问题。

2 个答案:

答案 0 :(得分:0)

似乎@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指出这一点。

答案 1 :(得分:0)

app / models / user.rb

include UserImageUploader[:image]
has_many :item

应该{​​{1}},对此不是很自信,但这可能就是您在数据库中找到空白列的原因。 has_many :items关系应默认为必需。