Rails 3,将局部变量传递给partial
可能重复:
Rails:对将locals传递给partials的语法感到困惑
我想将局部变量(模型中没有相关字段)传递给partial。
# infos/index.html.erb 'info', :locals => {:info => first, :img_style => "original"} %>
:img_style将是图像的html样式。
# infos/_info.html.erb img_style), info %> # and here goes code for normal iteration # etc
但它不起作用,它返回错误:
# GET /infos/ undefined local variable or method `img_style' for #<#:0xc470cc4>
它可以在不做多余部分的情况下完成吗?
对不起我的英语不好。 :P
编辑:
井模型信息没有:img_style字段
# db/schema.rb create_table "infos", :force => true do |t| t.string "title" t.text "description" t.integer "place_id" t.datetime "created_at" t.datetime "updated_at" t.string "image_file_name" t.string "image_content_type" t.integer "image_file_size" t.datetime "image_updated_at" t.text "short" end
EDIT2:
甚至简单
不行。
应用程序堆栈跟踪
app/views/infos/_info.html.erb:3:in `_app_views_infos__info_html_erb___1029249744_92158380_1472718' app/views/infos/index.html.erb:7:in `_app_views_infos_index_html_erb__184644561_92172050_0' app/controllers/infos_controller.rb:8:in `index'
EDIT3:
查看
# infos/index.html.erb {@img_style => @aimg_style } %> - 'info', :object => e %>
# infos/_info.html.erb ...
最后
这不起作用:
# infos/index.html.erb {:info => first, :img_style => @aimg_style } %>
这有效:
# infos/index.html.erb 'info', :locals => {:info => e, :img_style => "original"} %>
谁知道为什么?
我实际上只是在Rails 3中使用这种语法:
render "a_partial", :a_local_variable => whatever, :another_variable => another
这应该工作:
<%= render :partial => "info", :locals => { :img_style => "original" } %>
有了这个部分:
# infos/_info.html.erb <%= image_tag(info.image.url, :class => img_style), info %>
但是,如果您调用部分错误,请尝试将其作为部分错误:
# infos/_info.html.erb <%= image_tag(info.image.url(img_style)), info %>
我已经花了好几个小时; 在视图中, render :partial => ? , :locals => (....}
render :partial => ? , :locals => (....}
似乎你第一次打电话:
render :partial => ? without a locals hash
然后调用渲染:partial => ?
使用本地哈希本地哈希不传递给视图。
如果第一个调用包含一个本地哈希,其相同的变量设置为''
则第二个调用REAL值将起作用。
您的代码(您在第一行中显示的代码)应该有效。 没有错误。 我甚至自己测试过,它对我有用。
这种错误的通常原因是:
- 拼写错误的变量名称
- 从其他地方调用部分地方,你不通过:本地。
您的模型没有属性“img_style”这一事实并不重要。
我可以在你的infos/index.html.erb
看到你有两个你调用render :partial => 'info', :object => ...
地方render :partial => 'info', :object => ...
而你没有:locals here。 只是行号与您之前发布的堆栈跟踪不匹配,因此很难说哪个调用会导致问题。
我想这两个对render
方法的调用都需要修正。
在第一个,具体,并调用render :partial => "info"
而不是render "info"
。 这可能是Rails中的一个错误,但由于一些奇怪的原因,在这种情况下,本地似乎没有传递给视图。
在第二次render
只需添加:locals。
我相信问题是跟踪, info
调用。 它正在查找img_style
的info
对象。 你不需要它。
我喜欢使用partials,但最近也看到了辅助方法的美感,特别是在像这样的简单渲染中。
def info_image(info, class_name="original") image_tag(info.image.url, :class => class_name) end
然后就是
<%= info_image(first) %>
要么
<%= info_image(first, "anotherclass") %>
在视图中。 更清洁。
如果它变得更复杂。 您只需要在一个地方更改代码。