Topic: render db attribute to the view

I have a simple app where you can upload recipes

I have just integrated the gem terrarum to give me all the countries of the world within my country model. I have a relationship where a recipe has_one country and a country belongs to recipe. I am using nested forms from ryan bates and have had no problem getting information to show from my ingredients model and preparation model. But i cannot get the country name to display once i have created a new recipe

Code is as follows

Form

    <%= f.fields_for :country do |ff| %>

    <%= ff.label :country, "Country Of Origin" %>
    <%= collection_select(:country, :country_id, Country.all, :id, :name, :prompt => 'Please select country') %>   

    <% end %>

View

    <% @recipes.each do |r| %>
    <tr>
    <td><%= r.dish_name %></td>
    <td><%= country_name(r.country) %></td>
    <td><%= r.difficulty %></td>
    <td><%= r.preperation_time %></td>
    <td><%= ingredient_names(r.ingredients) %></td>
    <td><%= preperation_steps(r.preperations) %></td>
    <td><%= image_tag r.avatar.url(:thumb)%></td>
    </tr>

Helper

    def preperation_steps(preperations)
    if preperations
      preperation_array = preperations.map {|pre| pre.prep_steps}
      preperation_array.join("\n")
    end
    end

    def country_name(country)
    if country
      country_array = country.map {|c| c.country_name}
      country_array.join("\n")
    end
    end
    end

I have included my preparation helper as this works, so surely my country_name helper mirrors this? or do i not need to put a helper in for this?

recipe controller

    def new

    @recipe = Recipe.new
    @recipe.build_country
    @recipe.ingredients.build
    @recipe.preperations.build

    end

recipe model

    has_one :country
    has_many :ingredients
    has_many :preperations
    has_many :favourites

    attr_accessible :dish_name, :difficulty, :preperation_time, :ingredients_attributes,  :preperations_attributes, :country_attributes, :avatar

    accepts_nested_attributes_for :ingredients, :preperations, :country

if anyone can help it would be much appreciated

Thanks

Last edited by richlewis14 (2012-11-10 12:38:49)

Re: render db attribute to the view

In your view you call 'country' on the recipe object:

...
<td><%= country_name(r.country) %></td>
...

So you pass an instance of Country object to your helper method:

def country_name(country)
    if country
      country_array = country.map {|c| c.country_name}
      country_array.join("\n")
    end
end

And in the helper method you are calling 'map' (it is usually called on a collection) and you passed a Country object. that's why it does not work.
You can replace the call to country name in the view as follows:

...
<td><%= r.country.country_name %></td>
...

and it should work as expected.
HTH

Re: render db attribute to the view

Apologies for delay in response, had found solution soon after posting, thank you for your answer though