Topic: pass it as a block?

I am a new rails/ruby programmer, and therefor like to read the forums regularly, and have found an answer given in 3 of the last four posts I read gave the same answer, and I don't understand what it means, even though I have used it when making forms, etc.

Re: pass it as a block?

What do you mean? You should give some details so we know what you're talking about.

Anyways, I'll venture a guess.

Let's say in you have a controller called ProjectsController and model called Project.

In the index action of the controller, you might have:

def index
    @projects = Project.all
end

That will return an array of all the projects in your database. In your index.html.erb view, you probably want to show a project's name, so you do:

<%= @projects.name %>

. But it doesn't work and you get an error about "undefined method 'name' on Project::blahblahblah". That's because your working with multiple projects in the variable, not just one, so you need to pass it as a block:

<% for project in @projects %>
    <%= project.name %>
<% end %>

That is a very rails-way of doing a block. It says "For each project in @projects, return a project's name, then end." You can also do a more standard ruby block:

<% @projects.each do |project| %>
    <%= project.name %>
<% end %>

In this case, it does the same thing, but will be more portable between versions of rails or to other frameworks, if you are worried about that kind of thing. Be sure you keep your variable names consistent too. If a variable should have an array of multiple objects, then name it something plural. If it's just one, name it something singular. You'll save yourself a lot of headaches this way. I figured this out a few weeks ago and wrote a blog post about it if you like: http://techonamission.tumblr.com/post/2 … tiverecord

Change is a vector. You can have all the change in the world, but if it doesn't go in the right direction, what good is it? | techonamission.com