質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

1回答

4263閲覧

複数画像をcarrierwaveでアップロードすると同じものが参照されます(rails)

yamady

総合スコア176

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2017/05/19 03:30

編集2017/05/19 11:30

###前提・分からないこと

Ruby(RubyonRails)で食べログのような口コミサイト開発中です。
carrierwaveを使って、レストランページにて複数画像をアップロードしたいのですが、なぜか一つの画像を参照してしまいます。
アップロードはactive adminから行なっています。

開発環境:Ruby on Rails 5.0.0.1

① それぞれ画像をアップロードしても...
イメージ説明

② 一つの画像だけが参照されてしまいます
イメージ説明

別件ではありますが、画像と紹介しているレストランと結びつけたいのですが、下記の部分をアルバム名で選択をできるようにしたいと考えています。

イメージ説明

初歩的な質問ですみませんが、お助けくださいませ。

###該当するソースコード

アドミンのアルバム(app/admin/album.rb)

Ruby

1ActiveAdmin.register Album do 2 permit_params :album_name, :image_1, :image_2, :image_3, :image_4, :image_5, :image_6, :image_7, :image_8, :image_9 3 # See permitted parameters documentation: 4 # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters 5 # 6 # permit_params :list, :of, :attributes, :on, :model 7 # 8 # or 9 # 10 # permit_params do 11 # permitted = [:permitted, :attributes] 12 # permitted << :other if params[:action] == 'create' && current_user.admin? 13 # permitted 14 # end 15end

レストランのアドミン(app/admin/restaurant.rb)

Ruby

1ActiveAdmin.register Restaurant do 2 permit_params :id, :name, :image, :genre, :access, :hour, 3 :address, :phone, :website, 4 :description, :seats, :area_id, :album_id, :mapaddress, :latitude, :longitude, albums_attributes: [:image] 5 # See permitted parameters documentation: 6 # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters 7 # 8 # permit_params :list, :of, :attributes, :on, :model 9 # 10 # or 11 # 12 # permit_params do 13 # permitted = [:permitted, :attributes] 14 # permitted << :other if params[:action] == 'create' && current_user.admin? 15 # permitted 16 # end 17end

レストランのコントローラー(restaurant_controllers.rb)

Ruby

1class RestaurantsController < ApplicationController 2・・・ 3 def new 4 @restaurant = Restaurant.new(create_params) 5 9.times { @restaurant.albums.build } 6 end 7 8 private 9 10 def restaurant_params 11 params.require(:restaurant).permit(:id, :name, :image, :genre, :access, :hour, 12 :address, :phone, :website, 13 :description, :seats, :area_id, :album_id, :mapaddress, :latitude, :longitude, albums_attributes: [:image]) 14 end 15・・・ 16end

レストランのモデル(restaurant.rb)

Ruby

1class Restaurant < ApplicationRecord 2 has_many :reviews 3 belongs_to :area 4 belongs_to :album 5 mount_uploader :image, ImageUploader 6 geocoded_by :mapaddress 7 after_validation :geocode 8end

アルバムのモデル(album.rb)

Ruby

1class Album < ApplicationRecord 2 has_many :restaurants 3 mount_uploader :image_1, ImageUploader 4 mount_uploader :image_2, ImageUploader 5 mount_uploader :image_3, ImageUploader 6 mount_uploader :image_4, ImageUploader 7 mount_uploader :image_5, ImageUploader 8 mount_uploader :image_6, ImageUploader 9 mount_uploader :image_7, ImageUploader 10 mount_uploader :image_8, ImageUploader 11 mount_uploader :image_9, ImageUploader 12end

アルバムのマイグレーションファイル

Ruby

1class CreateAlbums < ActiveRecord::Migration[5.0] 2 def change 3 create_table :albums do |t| 4 t.string :image_1 5 t.string :image_2 6 t.string :image_3 7 t.string :image_4 8 t.string :image_5 9 t.string :image_6 10 t.string :image_7 11 t.string :image_8 12 t.string :image_9 13 14 t.timestamps 15 end 16 end 17end

アルバムアップローダー

Ruby

1class AlbumUploader < CarrierWave::Uploader::Base 2 3 # Include RMagick or MiniMagick support: 4 # include CarrierWave::RMagick 5 # include CarrierWave::MiniMagick 6 7 # Choose what kind of storage to use for this uploader: 8 storage :file 9 # storage :fog 10 11 # Override the directory where uploaded files will be stored. 12 # This is a sensible default for uploaders that are meant to be mounted: 13 def store_dir 14 "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" 15 end 16 17 # Provide a default URL as a default if there hasn't been a file uploaded: 18 # def default_url(*args) 19 # # For Rails 3.1+ asset pipeline compatibility: 20 # # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_')) 21 # 22 # "/images/fallback/" + [version_name, "default.png"].compact.join('_') 23 # end 24 25 # Process files as they are uploaded: 26 # process scale: [200, 300] 27 # 28 # def scale(width, height) 29 # # do something 30 # end 31 32 # Create different versions of your uploaded files: 33 # version :thumb do 34 # process resize_to_fit: [50, 50] 35 # end 36 37 # Add a white list of extensions which are allowed to be uploaded. 38 # For images you might use something like this: 39 # def extension_whitelist 40 # %w(jpg jpeg gif png) 41 # end 42 43 # Override the filename of the uploaded files: 44 # Avoid using model.id or version_name here, see uploader/store.rb for details. 45 # def filename 46 # "something.jpg" if original_filename 47 # end 48 49end

###追記でエラーが発生しました

いただいた通り、albumの下に入れ子を作ってみるとかなり複雑っぽくなってしまい、多々エラーが発生してしまいました。。泣
まず、直したいところは下記2点です。

・active admin上で、アルバムとレストランを紐付けたい
現在はアルバムを選択する項目が消えてしまいました。。下記はレストランを入力するフォームです。
イメージ説明

active_admin側はgemで

・アルバムの画像を表示させるエラーが出てしまいます
NoMethodErrorとなってしまい、ビューの書き方に問題があるかと考えられます。

・active admin上でアルバムを入力するビューになぜか、アルバムIDが不明に2つ出ています。
イメージ説明

ビュー

Ruby

1 <!-- Wrapper for slides --> 2 <div class="carousel-inner" role="listbox"> 3 <div class="item active"> 4 <%= image_tag @restaurant.image %> 5 </div> 6 <div class="item restaurant-image"> 7 <%= image_tag @restaurant.album.image_1 %> 8 </div> 9 <div class="item restaurant-image"> 10 <%= image_tag @restaurant.album.image_2 %> 11 </div> 12 <div class="item restaurant-image"> 13 <%= image_tag @restaurant.album.image_3 %> 14 </div> 15 <div class="item restaurant-image"> 16 <%= image_tag @restaurant.album.image_4 %> 17 </div> 18 <div class="item restaurant-image"> 19 <%= image_tag @restaurant.album.image_5 %> 20 </div> 21 <div class="item restaurant-image"> 22 <%= image_tag @restaurant.album.image_6 %> 23 </div> 24 </div>

■ レストラン側のコード

・レストランのモデル

Ruby

1class Restaurant < ApplicationRecord 2 belongs_to :area 3 has_many :album 4 mount_uploader :image, ImageUploader 5 geocoded_by :mapaddress 6 after_validation :geocode 7end

・レストランのコントローラー(restaurant_controllers.rb)

Ruby

1class RestaurantsController < ApplicationController 2・・・ 3 def restaurant_params 4 params.require(:restaurant).permit(:id, :name, :image, :genre, :access, :hour, 5 :address, :phone, :website, 6 :description, :seats, :area_id, :album_id, :mapaddress, :latitude, :longitude, albums_attributes: [:image]) 7 end 8・・・ 9end

・レストランとアルバムを紐付けるマイグレーションファイル
日付_album_id_to_restaurants.rb

Ruby

1class AlbumIdToRestaurants < ActiveRecord::Migration[5.0] 2 def self.up 3 add_column :restaurants, :album_id, :integer 4 add_index :restaurants, :album_id 5 end 6 7 def self.down 8 remove_index :restaurants, :column => :album_id 9 remove_column :restaurants, :album_id 10 end 11end

■ アルバム側のコード
・アルバムのモデル

Ruby

1class Album < ApplicationRecord 2 belongs_to :restaurant 3 has_many :album_contents 4 accepts_nested_attributes_for :album_contents 5end

・アルバムのコントローラー

Ruby

1class AlbumController < ApplicationController 2 def new 3 @album = Album.new(create_params) 4 9.times { @album.album_contents.build } 5 end 6 7 private 8 9 def create_params 10 params.require(:album).permit(album_contents_attributes: [:image]) 11 end 12end

・アルバムのマイグレーションファイル

Ruby

1class CreateAlbums < ActiveRecord::Migration[5.0] 2 def change 3 create_table :albums do |t| 4 t.integer :restaurant_id 5 6 t.timestamps 7 end 8 end 9end

・アルバムの入れ子となるアルバムコンテンツのモデル

Ruby

1class AlbumContent < ApplicationRecord 2 belongs_to :album 3 mount_uploader :image_1, AlbumContentUploader 4 mount_uploader :image_2, AlbumContentUploader 5 mount_uploader :image_3, AlbumContentUploader 6 mount_uploader :image_4, AlbumContentUploader 7 mount_uploader :image_5, AlbumContentUploader 8 mount_uploader :image_6, AlbumContentUploader 9 mount_uploader :image_7, AlbumContentUploader 10 mount_uploader :image_8, AlbumContentUploader 11 mount_uploader :image_9, AlbumContentUploader 12end

・アルバムコンテンツのマイグレーションファイル

Ruby

1class CreateAlbumContents < ActiveRecord::Migration[5.0] 2 def change 3 create_table :album_contents do |t| 4 t.integer :album_id 5 t.string :image_1 6 t.string :image_2 7 t.string :image_3 8 t.string :image_4 9 t.string :image_5 10 t.string :image_6 11 t.string :image_7 12 t.string :image_8 13 t.string :image_9 14 15 t.timestamps 16 end 17 end 18end

・アルバムとアルバムコンテンツを紐付けるマイグレーションファイル

Ruby

1class AddAlbumRefToAlbumContent < ActiveRecord::Migration[5.0] 2 def change 3 add_column :album_contents, :album, :refernces 4 end 5end

いろいろ反省しかありません。。
すみませんが、おたすけくださいませ。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

CarrierWaveは一つのレコードに一つの画像しか設定できません。
複数の画像を一つのレコードにひもづけたかったら、restrantに対して
Albumを複数用意して、そこに写真を紐づけてください。
(この場合Albumの下にalbaum_contensとかを作った方がいいのかな?)
nested_attributes_forなどを使うと実装が簡単です。
参考

下記の部分をアルバム名で選択をできるようにしたいと考えています。
これもコードを見せていただかないとわかりませんが

ruby

1f.select :album_id,@albams

ruby

1f.select :album_id,@albams.pluck(:name,:id)

とすればいいと思います。

投稿2017/05/19 08:36

moke

総合スコア2241

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

yamady

2017/05/19 09:33

mokeさま ありがとうございます。Carrier Waveの使い方を理解しておらず、恥ずかしい限りです。いま、あらたにAlbum_contentを作ろうと試みたのですが、下記のようなエラーが生じて進むことができません。。 これって、いかような処置が必要なのでしょうか>< SQLite3::SQLException: no such table: album_contents: ALTER TABLE "album_content" ADD "album_id" integer
moke

2017/05/19 09:39

こないだお教えしたサンプルはすでにあるテーブルに 参照idを追加するスクリプトです。 table等も作るには rails g model album_contents album_id:integer #他に必要そうなデータ と言った感じでmodelごと作りましょう。
yamady

2017/05/19 11:32

mokeさま、コメントいただき誠にありがとうございます。 アルバムコンテンツを作成してみたのですが、多々エラーに苦しむことになりました。。(反省 上記質問欄に追記いたしましたが、紐づけがだいぶ狂ってしまいました。。(反省
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問