kdweber89
kdweber89

Reputation: 2174

How to loop through values and linking to them using Rails and Haml

I have two models, Downtowns and Properties. The relationship is one-to-many, one downtown, many properties. I'm having trouble displaying and linking to a list of each downtown's properties on the downtown's show page.

Instead of an actual link to each property, I'm getting HTML text instead, displayed in what would almost appear to be a string, but no executable path.

Instead of getting downtown property 1 as a link, I get:

<a href="/downtowns/1/properties/1">downtown property 1</a>

My route file is:

resources :downtowns do
    resources :properties
  end

My downtown controller is:

def show
    @properties = Property.where(downtown: @downtown_id)
  end

  def new
    @downtown = Downtown.new
  end

  def create
    @downtown = Downtown.create(downtown_params)
    if @downtown.save
      redirect_to @downtown
    else
      render 'new'
    end
  end

  def downtown_params
    params.require(:downtown).permit(:name, :city)
  end

My properties controller is:

  def new
    @property = Property.new
  end

  def create
    @downtown = property.find(id)
    @property = Property.create(params[:property_params])
    @property.downtown_id = @downtown.id

    if @property.save
      redirect_to @property
    else
      render 'new'
    end
  end

  def show
  end

And finally my downtown show page:

%h2= @downtown.name

- if @downtown.properties.present?
  %p 
    = @downtown.properties.map {|property| link_to(property.name, downtown_property_path(property)) }.join("<br/>")
- else
  No downtowns for now. 

Upvotes: 0

Views: 66

Answers (1)

kdweber89
kdweber89

Reputation: 2174

Doing this in Haml is possible and not too difficult. The only thing that I was doing wrong was how I was formatting it.

I changed

    = @downtown.properties.map {|property| link_to(property.name, downtown_property_path(property)) }.join("<br/>")

to

- @downtown.properties.collect do |property|
      = link_to property.name, downtown_property_path(property)

Upvotes: 1

Related Questions