如何从ApplicationController使用嵌套属性的方法?

时间:2015-09-17 18:35:29

标签: ruby-on-rails ruby model-view-controller

如果我这样做 def calendar_sidebar @missed_dates_by_date = current_user.missed_dates.group_by {|i| i.date_missed.to_date} if current_user # I'm trying to call `missed_dates` method `date_missed` @date = params[:date] ? Date.parse(params[:date]) : Date.today if current_user end

undefined method 'missed_dates'

我得到[1] pry(main)> MissedDate.last id: 3, user_id: nil,

这是因为:

nil

我不知道如何使user_id不是belongs_to :level,或者是否有其他方法可以解决这个问题。

MissedDate belongs_to :habit和等级belongs_to :user以及与user_id相关联的习惯@missed_dates_by_date = current_user.habits.levels.date_missed.group_by {|i| i.date_missed.to_date}

作为一个新手,我在脑海中想到这样的事情会起作用:

undefined method 'levels'

但这给了<%= calendar @date do |date| %> <%= date.day %> <ul> <% @missed_dates_by_date[date].each do |missed_dates| %> # This is what I'm trying to get it to work for so that I can show in a calendar the date_missed <%= missed_dates.date_missed %> <% end %> </ul> <% end %>

_calendar.html.erb

 var class = windowwidth < 750 ? 'open' : 'otherclass';
 $parent
     .toggleClass(class)
     .trigger('shown.bs.dropdown', relatedTarget)

2 个答案:

答案 0 :(得分:2)

要通过另一个关联获取关联,我们必须在模型中声明它指定:through选项,如下所示:

class User < ActiveRecord::Base
  has_many :habits
  has_many :levels, through: :habits
  has_many :missed_dates, through: :levels
end

这样,ActiveRecord知道如何将错过的日期与用户关联,并且可以自动检索它们(user_id上没有MissedDate字段):

current_user.missed_dates.where(attribute: value)

您应该从user_id删除MissedDate,以避免与迁移混淆:

def up
  remove_column :missed_dates, :user_id
end

def down
  # insert the code to re-create the column
end

答案 1 :(得分:2)

您得到错误未定义方法missed_dates,因为您的用户没有此关联。

您应该像这样创建用户模型:

class User < ActiveRecord::Base
  has_many :missed_dates
end

你的MissedDate模型:

class MissedDate < ActiveRecord::Base
  belongs_to :user
end

在此之后,您可以创建关联对象:

@user = User.new
@user.missed_dates << MissedDate.new