Ruby on rails 如何使用嵌套属性';来自ApplicationController的方法?
在Ruby on rails 如何使用嵌套属性';来自ApplicationController的方法?,ruby-on-rails,ruby,model-view-controller,Ruby On Rails,Ruby,Model View Controller,在应用程序\u控制器中如果我这样做: 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(param
应用程序\u控制器中
如果我这样做:
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
我得到未定义的方法“错过日期”
这是因为:
[1] pry(main)> MissedDate.last
id: 3,
user_id: nil,
我不知道如何使用户id不为nil,或者是否有其他方法
MissedDate属于:级别
和级别属于:习惯和习惯属于:用户,该用户id与之关联
作为一名新手,我在脑海中想象这样的事情会奏效:
@missed_dates_by_date = current_user.habits.levels.date_missed.group_by {|i| i.date_missed.to_date}
但这给了未定义的方法“级别”
\u calendar.html.erb
<%= 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 %>
#这就是我想让它工作的原因,这样我就可以在日历上显示你错过的日期
要通过另一个关联获取关联,我们必须在指定选项的模型中声明它,如下所示:
class User < ActiveRecord::Base
has_many :habits
has_many :levels, through: :habits
has_many :missed_dates, through: :levels
end
您可能应该从MissedDate
中删除user\u id
,以避免与如下迁移混淆:
def up
remove_column :missed_dates, :user_id
end
def down
# insert the code to re-create the column
end
要通过另一个关联获取关联,我们必须在指定选项的模型中声明它,如下所示:
class User < ActiveRecord::Base
has_many :habits
has_many :levels, through: :habits
has_many :missed_dates, through: :levels
end
您可能应该从MissedDate
中删除user\u id
,以避免与如下迁移混淆:
def up
remove_column :missed_dates, :user_id
end
def down
# insert the code to re-create the column
end
由于您的用户没有此关联,因此您将获得错误未定义方法
错过的\u日期
您应该像这样创建用户模型:
class User < ActiveRecord::Base
has_many :missed_dates
end
class用户
以及您的MissedDate模型:
class MissedDate < ActiveRecord::Base
belongs_to :user
end
class MissedDate
在此之后,您可以创建关联对象:
@user = User.new
@user.missed_dates << MissedDate.new
@user=user.new
@user.missed_dates由于您的用户没有此关联,因此您将获得错误未定义方法missed_dates
您应该像这样创建用户模型:
class User < ActiveRecord::Base
has_many :missed_dates
end
class用户
以及您的MissedDate模型:
class MissedDate < ActiveRecord::Base
belongs_to :user
end
class MissedDate
在此之后,您可以创建关联对象:
@user = User.new
@user.missed_dates << MissedDate.new
@user=user.new
@user.missed_日期非常感谢!直到现在我才明白通过
是为了什么:]非常感谢!直到现在我才明白通过
是为了什么:]我已经知道了。埃利基尔给了我答案。谢谢你的帮助:]是的,我在贴出我的答案后看到了。我已经收到了。埃利基尔给了我答案。不过谢谢你的帮助:]是的,我在贴出答案后看到了。