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