前提・実現したいこと
現在、個人開発のためECサイトを作成しております。
現在、自身に管理者権限をもたせ、商品の登録などは全て管理者(自身)にて行うという機能実装を
持たせるため、以下のgemをインストールしました。
- rails_admin
- devise
- cancancan
※上記の導入については以下のサイトを参照しました。
https://www.y-hakopro.com/entry/2019/07/29/173525
gemはインストール済みで、また、"URL:localhost:3000/admin"にもアクセスすることができております。
画面(ナビゲーション欄)にもありますようにproductsテーブルに商品を登録するため、
本画面から入力を行い、保存ボタンをクリックしたところ以下のエラーが発生しました。
上記エラーを解決したいです。
これまでにbrandsテーブルには4つレコードを手入力にて登録しております。
(4つのブランドで4つの商品を登録)
5つめのブランドを使用して当該画面で保存・登録を実施しようとしたため
エラー画面では"5 is not a valid brand_id"と表示されております。
ちなみにナビゲーションにあるBrandなどは保存・登録ができており
DB(SequelProを使用)にも登録が反映されております。
補足情報(FW/ツールのバージョンなど)
rails -v : 5.2.4.2
rails_admin ~> 2.0
ruby -v : 2.5.1p57
該当のソースコード
実施した流れ・コードは以下の通りです。
■adminの導入
usersテーブルにadminカラムを追加
マイグレーションファイルを作成($ rails g migration AddAdminToUsers)
出来上がったマイグレーションファイルを編集
ruby
1class AddAdminToUsers < ActiveRecord::Migration[5.2] 2 def change 3 add_column :users, :admin, :boolean, default: false 4 end 5end
管理者専用アカウントの作成
deviseで通常通り新規アカウントを作成します
adminが0(false)になっていることを確認し、コンソールでadminの値を変更(0→1)
■cancancanの導入
app/models/ability.rbは以下のように記載
ruby
1class Ability 2 include CanCan::Ability 3 4 def initialize(user) 5 # Define abilities for the passed in user here. For example: 6 # can :manage, :session 7 # user ||= User.new # guest user (not logged in) 8 if user && user.admin? 9 can :access, :rails_admin 10 can :manage, :all 11 else 12 can :read, :all 13 end 14 # 15 # The first argument to `can` is the action you are giving the user 16 # permission to do. 17 # If you pass :manage it will apply to every action. Other common actions 18 # here are :read, :create, :update and :destroy. 19 # 20 # The second argument is the resource the user can perform the action on. 21 # If you pass :all it will apply to every resource. Otherwise pass a Ruby 22 # class of the resource. 23 # 24 # The third argument is an optional hash of conditions to further filter the 25 # objects. 26 # For example, here the user can only update published articles. 27 # 28 # can :update, Article, :published => true 29 # 30 # See the wiki for details: 31 # https://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities 32 end 33end
■rails_adminの導入
エラー画面に表示されているようなrailsadminのcontorllerは持っていません。
config/initializers/rails_admin.rbを以下のように記載。
ruby
1RailsAdmin.config do |config| 2 3 ### Popular gems integration 4 5 ## == Devise == 6 config.authenticate_with do 7 warden.authenticate! scope: :user 8 end 9 config.current_user_method(&:current_user) 10 11 ## == CancanCan == 12 config.authorize_with :cancancan 13 14 ## == Pundit == 15 # config.authorize_with :pundit 16 17 ## == PaperTrail == 18 # config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0 19 20 ### More at https://github.com/sferik/rails_admin/wiki/Base-configuration 21 22 ## == Gravatar integration == 23 ## To disable Gravatar integration in Navigation Bar set to false 24 # config.show_gravatar = true 25 26 config.actions do 27 dashboard # mandatory 28 index # mandatory 29 new 30 export 31 bulk_delete 32 show 33 edit 34 delete 35 show_in_app 36 37 ## With an audit adapter, you can add: 38 # history_index 39 # history_show 40 end 41end
試したこと
- products_controller.rbにnewとcreateアクションを記載
ruby
1class ProductsController < ApplicationController 2 3 def home 4 end 5 6 def index 7 @products = Product.includes(:brand, :main_spice, :season, :sex, :smell_impression, :smell_type, :use_scene).order('created_at DESC') 8 end 9 10 def show 11 end 12 13 def new 14 @product = Product.new 15 end 16 17 def create 18 @product = Product.new(product_params) 19 if @product.save 20 redirect_to products_path 21 else 22 render :new 23 end 24 end 25 26 def edit 27 @product = Product.find(params[:id]) 28 end 29 30 def update 31 @product = Product.find(params[:id]) 32 if @product.update(product_params) 33 redirect_to products_path, method: :put 34 else 35 render :edit 36 end 37 end 38 39 def destroy 40 end 41 42 private 43 44 def product_params 45 params.require(:product).permit(:name, :description, :image, :price, :stock_quantity, :brand_id, :sex_id, :season_id, :smell_type_id, :main_spice_id, :smell_impression, :use_scene_id) 46 end 47 48end
- テーブル間のアソシエーションを確認
product.rbを以下のように記載。
ruby
1class Product < ApplicationRecord 2 belongs_to :brand 3 belongs_to :sex 4 belongs_to :season 5 belongs_to :smell_type 6 belongs_to :main_spice 7 belongs_to :smell_impression 8 belongs_to :use_scene 9 validates :name, :description, :image, presence: true 10 11 belongs_to :user 12 13 enum brand_id: { 14 "---": 0, 15 BURBERRY: 1, 16 DIOR: 2, 17 CHANEL: 3, 18 "JO MALONE": 4, 19 Aesop: 5, 20 shiro: 6 21 }, _prefix: true 22 23 enum sex_id: { 24 "---": 0, 25 "女性": 1, 26 "男性": 2, 27 "ユニセックス": 3, 28 }, _prefix: true 29 30 enum seoson_id: { 31 "---": 0, 32 "春": 1, 33 "夏": 2, 34 "秋": 3, 35 "冬": 4, 36 }, _prefix: true 37 38 enum smell_type_id: { 39 "---": 0, 40 "フルーティー": 1, 41 "フローラル": 2, 42 "ウッディ&オリエンタル": 3, 43 "シトラス": 4, 44 "シプレ&フゼア": 5, 45 }, _prefix: true 46 47 enum main_spice_id: { 48 "---": 0, 49 }, _prefix: true 50 51 enum smell_impression_id: { 52 "---": 0, 53 "エレガント": 1, 54 "キュート": 2, 55 "セクシー": 3, 56 "スマート": 4, 57 "ワイルド": 5, 58 "クール": 6, 59 }, _prefix: true 60 61 enum use_scene_id: { 62 "---": 0, 63 "オフィス": 1, 64 "デート": 2, 65 "デイリー": 3, 66 "パーティー": 4, 67 "リラックス": 5, 68 }, _prefix: true 69end
また、マイグレーションファイルは以下のようにUPしております。
ruby
1class CreateProducts < ActiveRecord::Migration[5.2] 2 def change 3 create_table :products do |t| 4 t.string :name, null: false 5 t.text :description 6 t.text :image 7 t.integer :price 8 t.integer :stock_quantity 9 t.references :brand, foreign_key: true 10 t.references :sex, foreign_key: true 11 t.references :season, foreign_key: true 12 t.references :smell_type, foreign_key: true 13 t.references :main_spice, foreign_key: true 14 t.references :smell_impression, foreign_key: true 15 t.references :use_scene, foreign_key: true 16 t.timestamps 17 end 18 end 19end
外部キーに設定されたキーがいる親テーブルは以下のように設定しております。
例えば、Brandモデルであれば以下の通りです。
brand.rb
ruby
1class Brand < ApplicationRecord 2 has_many :products 3end
マイグレーションファイル
ruby
1class CreateBrands < ActiveRecord::Migration[5.2] 2 def change 3 create_table :brands do |t| 4 t.string :name 5 t.timestamps 6 end 7 end 8end
検索したりしていたのですが、解決できませんでした、、、
ご教示のほど、よろしくお願いいたします。
あなたの回答
tips
プレビュー