■解決したいこと
Ordersテーブルより任意のuser_idを取得する。
カレントユーザーが投稿した音楽ではなくかつ音楽購入している場合は「SOLD OUT」を表示する。
■仮説と検証作業の結果
カレントユーザーが投稿した音楽の場合は金額を表示。(できている)
カレントユーザーが投稿した音楽ではなくかつ音楽を購入していない場合は
購入ページへのリンクになっている金額を表示。(できている)
Ordersテーブルのレコードにアクセスできていない。
musicsControllerにOrdersテーブルからレコードを取得する記述ができていない
ruby
1@order = Order.new(order_params) 2 3def order_params 4 params.permit(:user_id, :music_id).merge(user_id: current_user.id, music_id: params[:music_id]) 5 end
この記述だとテーブルの中身ではなくカレントユーザーIDのみが取得できている状態にあり、
@order.music_idを見るとわかるように
music_idの値もnilのままである。
ruby <musicsController>
1def index 2 @order = Order.new(order_params) 3 @musics = Music.includes(:user).order('created_at DESC') 4 query = 'SELECT * FROM musics' 5 # @musics = Music.find_by_sql(query) 6 end 7 8private 9 10 def order_params 11 params.permit(:user_id, :music_id).merge(user_id: current_user.id, music_id: params[:music_id]) 12 end
html <music/index>
1<div class="info_show4"> 2 <% if user_signed_in? && current_user.id != music.user_id %> 3 <% if user_signed_in? && music.id == @order.music_id %> 4 <%= @order.user_id %> 5 <% else %> 6 <%= link_to "¥#{music.price}", music_orders_path(music.id) %> 7 <% end %> 8 <% else %> 9 <%= "¥#{music.price}" %> 10 <% end %> 11 </div>
ruby <music.rb>
1class Music < ApplicationRecord 2 belongs_to :user 3 has_many :tracks, dependent: :destroy 4 has_many :comments, dependent: :destroy 5 has_many :favorites 6 has_many :order 7 has_one_attached :image 8 9 with_options presence: true do 10 validates :title, length: { maximum: 22 } 11 validates :image 12 validates :artist_name, length: { maximum: 22 } 13 validates :price, format: { with: /\A[0-9]+\z/ }, 14 numericality: { only_integer: true, greater_than_or_equal_to: 500, less_than_or_equal_to: 50_000 } 15 end 16 17 validates :cd_type_id, numericality: { other_than: 1 } 18 19 extend ActiveHash::Associations::ActiveRecordExtensions 20 belongs_to :cd_type 21 22 validate :image_content_type, if: :was_attached? 23 24 def image_content_type 25 extension = ['image/png', 'image/jpg', 'image/jpeg'] 26 errors.add(:image, 'の拡張子が間違っています') unless image.content_type.in?(extension) 27 end 28 29 def was_attached? 30 image.attached? 31 end 32 33 def favorited_by?(user) 34 favorites.where(user_id: user.id).exists? 35 end 36end
ruby <order.rb>
1class Order < ApplicationRecord 2 has_one_attached :image 3 attr_accessor :token 4 belongs_to :music 5 belongs_to :user 6 7 8 with_options presence: true do 9 validates :token 10 validates :music_id 11 validates :user_id 12 end 13end
ordersテーブル
https://gyazo.com/e44ce1f035a448db91a7bc9410af5818
musicテーブル
https://gyazo.com/4509c471019f6180145e6f639e34cd7a
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。