I'm fairly new to Rails, and I was confused as to how I could pass local variables outside the if...else statement. It looks like creating a method in the helper file is the conventional way to do this, but I wasn't sure how to do this.
So I'm trying to get the Author of a Mission. If the author of a mission doesn't exist, I want to use the author of its parent Syllabus (missions belong to syllabus). And then I want to print out the username of that author. I was able to do this when I was dealing with only one mission, like:
//controller
@mission = Mission.first
if !@mission.author.blank?
@author = @mission.author
else
@author = @mission.syllabus.author
end
//view
<%= @author.username %>
but I wasn't sure how to do this when I was dealing with a foreach loop:
//controller
@mission = Mission.all
//view
<% @mission.each do |mission| %>
..(where do I put the logic of finding author? I can't put it in my controller anymore and it won't pass the @author variable outside the if else statement if I put the logic here in the view)..
<%= @author.username %>
<% end %>
My futile attempt was to create a helper:
def author_getter(mission_id)
@mission = Mission.find(params[:mission_id])
if !@mission.author.blank?
@author = @mission.author
return @author
else
@author = @mission.syllabus.author
return @author
end
end
and putting the below inside the loop
<%= author_getter(mission) %>
However, this didn't work. What would be the best way to pass on a variable outside the if...else statement?