简体   繁体   中英

Access image from different view in a view with paperclip gem ruby on rails

I'm new in Ruby on Rails and learning it. I want to access a table with images stored by paperclip gem in another view, for example in my application, I have the causes controller, I can access the image in the view causes stored in the table by this code:

 =image_tag @cause.images.first.image.url(:thumb), 

But i have access too, the images stored in the table from a profile controller. So, how do i access the object of view Profiles in the view Causes? I try in the causes controller:

-> @profile = Profile.all -> =image_tag @profile.images.first.image.url(:thumb), 

but not work, so friends, how do i resolve this problem? Thanks.

You are sending Profile.all into @profile that means @profile is going to be an array of profile objects. your method images will work on one object of Profile class, not on multiple. You need to select the proper profile and assign it to @profile. For EX :

@profile = Profile.first # just taking the first profile, you can select any.

In view , now you can use this @ profile to get an image.

Firstly, in the causes controller, pluralize @profile because Profile.all will return an array of all profiles. ie change @profile = Profile.all to @profiles = Profile.all

Because @profiles is an array, you need to iterate through each array item in the view Causes:

<% @profiles.each do |profile| %>
  <%= image_tag profile.images.first.image.url(:thumb) %>
<% end %>

If you only intend on returning a single profile image then you will need to specify which profile in the controller. ie

@profile = Profile.first

or if the cause model belongs to the profile model:

@profile = Profile.find(params[:profile_id])

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