RspecでJsonを返したいのですが、NoMethodError:
undefined method `status' for #<ActiveRecord::Associations::CollectionProxy []>がでてきてしまいます。
ruby
1class Entry < ApplicationRecord 2 belongs_to :user, class_name: :User, foreign_key: :user_id 3 belongs_to :offer, class_name: :Offer, foreign_key: :offer_id 4 belongs_to :recruit, class_name: :Recruit, foreign_key: :recruit_id 5 6 scope :active, -> { where(is_deleted: 0) } 7 8 class << self 9 def users_entry(user_id) 10 where(user_id: user_id) 11 end 12 end 13 14 def pre_status 15 self.status.to_sym 16 end 17 18 def pre_result 19 self.result.to_sym 20 end 21end
ruby
1class User::OffersController < ApplicationController 2 before_action :set_user_user 3 4 def show 5 is_login = @login_user ? true : false 6 offer = Offer.find(params[:id]) 7 recruits = offer.recruits.active 8 # @entry = recruits.entries 9 render json: { 10 work: offer_as_json(offer, is_login), 11 recruits: recruits_as_json(recruits, is_login), 12 errors: [] 13 } 14 end 15 16 def create_entry 17 entry = Entry.new({ 18 user_id: @login_user.id, 19 offer_id: params[:id], 20 recruit_id: params[:recruit_id] 21 }) 22 23 if entry.save! 24 render json: { success: true } 25 else 26 render json: { success: false, messages: entry.errors.full_messages } 27 end 28 end 29 30 private 31 def set_user_user 32 if params[:token].present? 33 @login_user = UserToken.find_by(token: params[:token]).user 34 else 35 @login_user = nil 36 end 37 end 38 39 def recruits_as_json recruits, is_login 40 recruits.map{|recruit| 41 recruit_as_json recruit, is_login 42 }.as_json 43 end 44 45 def recruit_as_json recruit, is_login 46 entry = is_login ? recruit.entries.users_entry(@login_user.id) : nil 47 { 48 id: recruit.id, 49 title: recruit.title, 50 e_st: entry.present? ? entry.pluck(:status).first : "test", 51 r_st: entry.present? && entry.pluck(:result) ? entry.pluck(:result).first : "pending", 52 } 53 end 54end 55
spec
ruby
1require 'rails_helper' 2 3RSpec.describe "User::Offer", type: :request do 4 describe "GET /user_offer" do 5 let!(:user) {create(:user)} 6 let!(:offer) { create(:offer_b) } 7 let!(:recruits) do 8 FactoryBot.create_list(:recruit, 3) 9 end 10 let!(:entry) {create(:entry)} 11 let(:res) { JSON.parse(response.body).deep_symbolize_keys } 12 context "正常系" do 13 it "詳細が有効" do 14 get '/api/user/offers/2' 15 pp JSON.parse(response.body) 16 expect(res).to eq( 17 { 18 :work => { 19 id: offer.id, 20 offer_name: "offer_name" 21 }, 22 :recruits =>[ 23 { 24 id: 1, 25 title: "title", 26 entry_status: "pending", 27 result_status: "pending" 28 }, 29 { 30 id: 2, 31 title: "title", 32 e_st: "pending", 33 r_st: "pending" 34 } 35 ], 36 errors: [] 37 } 38 ) 39 end 40 end 41 end 42end
こちらのdef recruit_as_json recruit, is_loginの中のe_st: recruit.entries.status,の書き方が悪いのだと思うのですが、どう直したらいいのかわからず困っています。
少しでもアドバイスなどいただければ助かります。
他の必要なデータありそうでしたら言ってください。
以上よろしくお願いいたします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/03 06:27
2018/12/03 06:48
2018/12/03 08:19
2018/12/03 08:51