Hi -- I'm very new to Rails. I'm using a simple project to get acquainted. In this project what it seems to me that I want to do is to have an action return a chunk of dynamically-generated html code complete with dynamic content, html tags, etc. Of course, it is intended that this content will then be incorporated into one or more views. I would think that this would be a very common need. Since I'm not really finding anything on this, I would first like to know if I'm heading off in the wrong direction. If what I want to do is reasonable; then, I'd like to know how to do it. I could easily develop the dynamic content and send it to the console with a series of puts statements at various strategic locations in my action. However, I don't want to do that. I want to RETURN the dynamic code so that I can incorporate it into views. If this is something that is commonly done, could someone please square me away on the proper methodology for handling it? Thanks for any input. ... doug
on 2007-03-04 04:23
on 2007-03-04 05:47
Your way of working goes against how Rails works, and when you do that you'll find Rails working against you rather than with you. Here's how I would achieve what you want: 1. In the controller, do the logic you need to setup for generating your HTML - whatever that logic is 2. In the view code, you will take what variables you setup in the controller, and use those to generate the HTML A simple example - Display the current user's name: Your way: 1. In the controller, find the current user and build some HTML - @username_html = "<b>username</b>" 2. In the view, put the username HTML on the page: <%= @username_html %> The Rails way: 1. Controller code: get the current user into @user - @user = User.find(1) 2. View code, display the user's name: <b><% =@user.name %></b> If your view logic starts to get complex (more than simple loops and if cases), you can build a helper method (in the _helper.rb file) to make the code easier to work with. The key is to keep code that controls what's going on in your Controller, and code that generates what the user sees in your Views.
on 2007-03-04 21:22
Thanks, Tom, for your very helpful post. It's obvious that I am not yet thinking in Rails. Once I get my mind wrapped around it I'll be OK. Your post was very helpful because it addressed philosophically where I was straying from the beaten path. I just need to get into the Rails way of doing things and all will be well. Thanks again. ... doug
on 2007-03-05 22:00
Doug, Technically you should think about this, not from a "Rails" point of view, but rather understand that Rails incorporates the Model View Controller (MVC) architectural pattern. When you understand that then you will understand Rails implementation of MVC. See: http://en.wikipedia.org/wiki/Model-view-controller