Rails 5.2.4.4
ruby 2.5.1p57
sqlite3
行いたい事: Carrierwaveを使って複数のimageをアップロード
エラー : undefined method `url' for nil:NilClass.
どなたか分かる方いらっしゃいましたらご回答お願いします。
new.html.erb <%= form_for [:admins,@item], local: true do |f| %> <%= render 'shared/errors', object: f.object%> <%= f.label :name %> <%= f.text_field :name, class: 'form-control mb-3'%> <%= f.label :price %> <%= f.text_field :price, class: 'form-control mb-3'%> <%= f.file_field :imgs, multiple: true %> <%= f.label :Video_url %> <%= f.text_field :Video_url, class: 'form-control' %> <%= f.label :discription %> <%= f.text_area :discription, class: 'form-control' %> <%= f.submit "Create my item", class: "btn btn-primary d-block" %> <% end %>
index.html.erb <% @items.each do |item| %> 問題: undefined method `url' for nil:NilClass. 1..<%= link_to(image_tag(item.imgs[0].url || "19.jpg"), item, class: "img-responsive") %> このコードは一応動くが、imgが大きすぎる 2..<%= link_to(image_tag(item.imgs[0].to_s || "19.jpg"), item, class: "img-responsive") %> 動かない。なぜ? 3..<%= link_to(image_tag(item.imgs[0].thumb.to_s || "19.jpg"), item, class: "img-responsive") %> <% end %> このindex.html.erbのコードでなぜ3番のコードが動かないのか。そしてurlとto_sの違いを教えて頂けますか?
controller def new @item = current_admin.items.build end def create @item = current_admin.items.build(item_params) if @item.save flash[:success] = "Your item is posted" redirect_to root_path else render 'new' end end private def item_params params.require(:item).permit(:name, :price, :discription, :Video_url,{imgs: []}) end
image_uploader class ApplicationUploader < CarrierWave::Uploader::Base storage :file def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end end class ImageUploader < ApplicationUploader process resize_to_fit: [800, 800] # item/index version :thumb do process resize_to_fill: [300,400] end # basket/show version :thumb50 do process resize_to_fill: [120,150] end end
(my data is sqlite3) item.rb mount_uploaders :imgs, ImageUploader serialize :imgs, JSON
my rails c [1] pry(main)> item1 = Item.first [6] pry(main)> item1.imgs[0].url => "/uploads/item/imgs/71/su1.jpg" pry(main)> item1.imgs[1].url => "/uploads/item/imgs/71/top.jpg"
あなたの回答
tips
プレビュー