Gustavo Reyes
Gustavo Reyes

Reputation: 1344

How to call a ruby on rails controller when view is loaded?

I am pretty new to Rails, basically what I want to do is pretty simple, when the view is loaded I want it to call a controller that executes a ruby script and render the image generated by this script on my view, is this possible? Or should I call the script before the view is loaded and just retrieve the generated image?

Upvotes: 0

Views: 2082

Answers (3)

Muhamamd Awais
Muhamamd Awais

Reputation: 2385

First of all what i would suggest you to go and learn here a link for your help ruby on rails tutorial

Answer to your problem In rails controllers are loaded first, each view is associated to some controller action, forexample if you have users controller(app/controllers/users_controller.rb) and in show you want to display the users image as a profile picture, what you can do is

def show
  @user = User.find(params[:id])
end

and in its corresponding view(app/views/show.html.erb)

<img src = <%= @user.image_path %> />

Upvotes: 2

Sayuj
Sayuj

Reputation: 7622

In RoR a controller action is rendering the view, so you can set it at the initial load itself.

For example, you have the Users controller and you need to show all users images in the index view.

controllers/users_controller.rb

def index
  @users = User.all
end

views/users/index.hrml.erb

<% @users.each do |user| %>
  <img src=<%= user.image_path %>> </img>
<% end %>

Upvotes: 0

Holger Sindbaek
Holger Sindbaek

Reputation: 2344

I would retrieve the image on load of the page, hide it with css and load it anytime you want with javascript. I don't see a big reason for not calling it on the load of the page.

Upvotes: 0

Related Questions