简体   繁体   中英

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.

<% @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. Using m.id doesn't work because the route is expecting a hash.

Not entirely sure how to do this. Other posts on SO refer to unsaved instances and such, which aren't really relevant to this.

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. 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 :

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. :)

That being said - it will still not work, but you should get a different problem now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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