2015-01-21 10 views
0
class Activity < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :contract 
    belongs_to :customer 
    has_one :expense 
end 

class Expense < ActiveRecord::Base 
    belongs_to :activity 
end 

나는 ExpensesController 한 Expense을 만들려고 할 때 나는 undefined method expense' for nil:NilClass를 얻을 :정의되지 않은 메서드 - belongs_to의 assocation

if !activity.try(:expense) 
     activity.expense.create(ref: @current_date, year: session[:current_year], month: session[:current_month], 
           days:["1", "2"]) 
end 

을 나는이 서버가 어떤에서 expense를 호출하려고하기 때문에 일반 가정하자 즉, nil입니다.

문제는 원래 코드가 내 것이 아니라는 것입니다. ActivityExpenses 사이에 연결을 추가해야했습니다. 새로운 Expenses을 만들려면 어떻게해야합니까?

편집 : 여기에 ExpensesController

def show 
if session[:current_month] == nil && session[:current_year] == nil 
    session[:current_month] = params[:month] 
    session[:current_year] = params[:year] 
else 
    if session[:current_month] != params[:month] || session[:current_year] != params[:year] 
    session[:current_month] = params[:month] 
    session[:current_year] = params[:year] 
    end 
end 

@calendar, @previous_month, @next_month, @month_name = get_calendar(session[:current_year], session[:current_month]) 
@current_date = @month_name + " " + session[:current_year] 

# If expense does not exist, create one with current month 
activity = Activity.where(month: params[:month], year: params[:year]).first 
if activity.try(:expense) 
    @nb_days = 0 
    @calendar.each do |c| 
     @nb_days += 1 
    end 
else 
    activity.expense.create(ref: @current_date, year: session[:current_year], month: session[:current_month], 
          days:[""]) 
end 
@expense = activity.expense 
end 

답변

1

show 행동의 전체 코드는 내가 올바르게 읽고 있어요 경우 activity 변수가 널 (null) 세트입니다입니다. 문제가 여기에 있다고 생각합니다 :

activity = Activity.where(month: params[:month], year: params[:year]).first 

이것은 레코드를 반환하지 않습니다.