has_one的未定义方法 - belongs_to关联

时间:2015-01-21 16:34:57

标签: ruby-on-rails has-one

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中创建一个undefined method expense' for nil:NilClass时,我得到Expense

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

编辑:这里是show

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 个答案:

答案 0 :(得分:1)

如果我正确读取此内容,则您的activity变量为空集。我认为问题在于:

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

这不会返回任何记录。