无法理解在 rails 视图中的同一控制器中使用links_to过滤器内容的工作原理。我的代码如下:
# index.html.erb (链接导航区)
<nav>
<%= link_to 'Daily Monitoring', root_path(:category => "dailymonitoring") %>
<%= link_to 'Smoke Tests', root_path(:category => "smoketests") %>
</nav>
# index.html.erb (续)
<ul id="results">
<% if @reportlinks == "dailymonitoring" %>
# dailymonitoring content
<% elsif @reportlinks == "smoketests" %>
# smoketests content
<% end %> <!-- end conditional -->
</ul>
# reports_controller.rb
if params[:category]
@reportlinks = Report.where(:category => params[:category])
else
@reportlinks = Report.all
end
# 模型 (report.rb)
class Report
include ActiveModel::Model
attr_accessor :reports, :smokereports
belongs_to :reports, :smokereports, :reportlinks
end
我得到的错误是报告:类的未定义方法"belongs_to"和<顶部(必需)>错误。不涉及数据库。我只是想让它知道我想点击任何链接,并且只过滤该 if/else 语句中的内容块。
我是否需要创建一个新的控制器才能使 if/else 语句正常工作?如果需要更多代码来更好地理解,请告诉我。谢谢。
belongs_to
在 ActiveRecord::Associations
中定义,这是 ActiveRecord
的一部分。您手动包含不提供任何关联相关功能的ActiveModel::Model
。
包括对象与 ActionPack 交互所需的接口,使用不同的 ActiveModel 模块。它包括模型名称自省、转换、翻译和验证。除此之外,它还允许您使用属性哈希初始化对象,就像ActiveRecord一样。
假设您不需要整个ActiveRecord
数据库持久性功能,但需要关联样式,则需要手动处理它。
因此,您必须定义自己的方法来附加/删除关联记录并跟踪它们。
ActiveRecord 的关联功能与数据库持久性紧密相关。