Ruby on rails 如何在Rails中访问助手方法?
我有一个rails应用程序,带有一个Ruby on rails 如何在Rails中访问助手方法?,ruby-on-rails,Ruby On Rails,我有一个rails应用程序,带有一个main\u控制器,用于向我的应用程序主页提供内容。我想访问一组图像,因此我在控制器中创建了以下方法: def featured_illustrations #future implementation: get images where featred == true @featured_illustrations << Illustration.find(152) @featured_illustrations <
main\u控制器
,用于向我的应用程序主页提供内容。我想访问一组图像,因此我在控制器中创建了以下方法:
def featured_illustrations
#future implementation: get images where featred == true
@featured_illustrations << Illustration.find(152)
@featured_illustrations << Illustration.find(272)
@featured_illustrations << Illustration.find(275)
respond_to do |format|
format.html
format.json { render :json => @featured_illustrations }
end
end
helper_method :featured_illustrations
以及特色图片
部分中的以下代码:
<div class="featured">
<% @featured_illustrations.each do |illustration| %>
<!-- somc code to print images -->
<% end %>
</div>
我以前从未与助手合作过,因此非常感谢您的指导。谢谢
更新:
我已删除了mainheloper
,但现在在尝试加载页面时出现以下错误:
uninitialized constant MainHelper::MainController
undefined method `each' for nil:NilClass
Extracted source (around line #2):
1: <div class="featured">
2: <% featured_illustrations.each do |illustration| %>
3: <div class="feature-image" id="feature-one">152</div>
4: <div class="feature-image" id="feature-two">272</div>
5: <div class="feature-image" id="feature-three">275</div>
未定义nil:NilClass的方法'each'
提取的源(第2行附近):
1:
2:
3: 152
4: 272
5: 275
关于原因有什么想法吗?简单回答:在您发布的错误中,看起来您没有迭代正确的变量。您已将特色插图指定给实例变量(它们以@开头),而不是您正在使用的局部变量 更改:
<% featured_illustrations.each do |illustration| %>
app/views/main/featured_insulations.html.erb
<div class="featured">
<% @featured_illustrations.each do |illustration| %>
<!-- somc code to print images -->
<% end %>
</div>
最后,如果您还没有这样做,您可能想看看Rails如何使用REST和资源路由。你可以在网上找到很多 虽然您的方法不再导致错误,但即使清除了ruby代码部分,也无法显示部分。这就是我如何称呼parital:
“主要/特色插图”,:collection=>@characterized_inspections%>
您得到的代码片段是ERB,这意味着您首先呈现另一个模板,然后将@characterized_inspections
作为集合对象传递给characterized_inspections
部分。那个片段在哪个文件中?此外,partials在前面用下划线命名。您需要将app/views/main/featured_inspections.html.erb
重命名为app/views/main/_featured_inspections.html.erb
,渲染器才能拾取它。
<% @featured_illustrations.each do |illustration| %>
def featured_illustrations
@featured_illustrations = Illustration.where(featured: true)
respond_to do |format|
format.html
format.json { render :json => @featured_illustrations }
end
end
<div class="featured">
<% @featured_illustrations.each do |illustration| %>
<!-- somc code to print images -->
<% end %>
</div>
match '/featured_illustrations/', to: 'main#featured_illustrations'