Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

alborz
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
alborz
Full Stack JavaScript Techdegree Graduate 30,885 Points

Creating a Reddit clone - stuck trying to display url page once user clicks the displayed link's title on the home page

Hi - I'm building a Reddit clone in Rails 4.2 and am stuck trying to show the url once a user clicks the title's link.

Here is my code below for links controller:

class LinksController < ApplicationController
    def index
        @links = Link.all
    end

    def new
        @link = Link.new
    end

    def create
        @link = Link.new(link_params)

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

    def show
        @link = Link.find(params[:id])
    end

    private

    def link_params
        params.require(:link).permit(:title, :url)
    end
end

Link controller's index view:

<h1>Home page.</h1>

<ul>
    <% @links.each do |link| %>
        <li><%= link_to link.title, link_path(link) %></li>
    <% end %>
</ul>

<%= link_to "Submit a new link", new_link_path %>

Currently, when I click the link I get an error that says:

ActiveRecord::RecordNotFound in LinksController#show

Couldn't find Link with 'id'=http://reddit

Thanks

Are links meant to link internally (similar to reddit self posts) or are they external links?

alborz
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
alborz
Full Stack JavaScript Techdegree Graduate 30,885 Points

I want it so that when a user clicks on the link from the lists displayed they are redirected to that page's website, such as another news site for an article. I think that's external?

1 Answer

You need to pass the Link instance's URL into link_to. Assume url is the field in your links table then it would look like:

<li><%= link_to link.title, link.url %></li>

The link_path method is used to generate an internal URL based on an active record model object. By default this usually means something along the lines of: "/links/123" where "123" is the ID of the Link record. Since you have external URLs you won't need to use a URL or path helper method and can just directly pass the URL into link_to as shown above.

Hope that helps.

EDIT: "ID" not "idea"