简体   繁体   English

将哈希传递到Rails中的路线

[英]passing a hash to a route in rails

In the preview action in my controller, I have 在控制器的预览动作中,我有

@models = Model.all

In the view, Im trying to loop through all the models, draw out their associated images, and use those to link_to their own profiles. 在视图中,Im试图遍历所有模型,绘制出它们的关联图像,并使用这些图像将其链接到自己的配置文件。

<% @models.each do |m| %>
<div> <%= link_to(image_tag (m.avatar.url(:thumb)), model_path())%> </div>
<% end %>

I need to pass in the id of each model to the route. 我需要将每个模型的ID传递给路线。 Using m.id doesn't work because the route is expecting a hash. 使用m.id无效,因为路由需要哈希值。

Not entirely sure how to do this. 不太确定如何执行此操作。 Other posts on SO refer to unsaved instances and such, which aren't really relevant to this. SO上的其他帖子都引用了未保存的实例等,与这些实例并没有真正的关系。

Try changing your view code from this: 尝试从此更改视图代码:

<% @models.each do |m| %>
<div> <%= link_to(image_tag (m.avatar.url(:thumb)), model_path())%> </div>
<% end %>

To: 至:

<% @models.each do |m| %>
<div> <%= link_to(image_tag(m.avatar.url(:thumb)), model_path(m))%> </div>
<% end %>

As usual the error might be in a completely different place - your brackets. 像往常一样,错误可能出现在完全不同的地方-您的括号中。

model_path can accept both list of attributes and a hash. model_path可以接受属性列表和哈希。 Most likely you think it is expecting a hash due to the error message (which you should include in the question). 您最有可能认为由于该错误消息(您应该在问题中包括该信息),因此期望哈希值。 In fact however, you are passing the path to the image_tag , not to the link_to : 但是实际上,您正在将路径传递到image_tag ,而不是link_to

link_to(image_tag (m.avatar.url(:thumb)), model_path())

is parsed as 被解析为

link_to( image_tag(m.avatar.url(:thumb), model_path()) )

While: 而:

link_to(image_tag (m.avatar.url(:thumb)), model_path())

is parsed as 被解析为

link_to( image_tag(m.avatar.url(:thumb)), model_path() )

This space between a method name and a bracket is a silent killer. 方法名称和方括号之间的空格是一个沉默杀手。 It is a image_tag which is expecting a hash in a second argument. 这是一个image_tag ,它在第二个参数中期望有哈希值。 :) :)

That being said - it will still not work, but you should get a different problem now. 话虽如此-它仍然无法正常工作,但您现在应该遇到另一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM