Building a Reddit Clone Pt.2

We should next start to put some links into our application, to let people click on sign in and sign out links, viewing their account details and submitting links when signed in.

<% if user_signed_in? %>
<ul>
<li><%= link_to ‘Submit link‘, new_link_path %></li>
<li><%= link_to ‘Account‘, edit_user_registration_path %></li>
<li><%= link_to ‘Sign out‘, destroy_user_session_path, :method => :delete %></li>
</ul>
<% else %>
<ul>
<li><%= link_to ‘Sign up‘, new_user_registration_path %></li>
<li><%= link_to ‘Sign in‘, new_user_session_path %></li>
</ul>
<% end %>

 

The block of code given above consists of embedded ruby , to modify front-end HTML files to our needs e.g. links, marked by: <%>

Translating the code it would mean: If the user is signed in, view him the ‘Submit link‘, ‘Account‘, and ‘Sign out‘ links. Devise set up the paths allready, how convenient. The ‘Sign out‘ link is a bit special due to its :method and :delete symbols. It basically sets up a method which would destroy the users session to ultimately sign out of the app.

If the user is not signed in, view him only ‘Sign up’ and ‘Sign in’ links, to guide him to registration and a sign in template.

 

A Ruby Symbol: It’s almost the same like in the real world, where symbols represent things. Symbols are very commonly used to represent states of objects like:

game.status = :ended

game.status = :cancelled

In comparison to variables, it’s not needed to define a symbol you can just use it.

 

Next, editing the links_controller.rb file and within it, the new and create method.

def new
@link = current_user.links.build
end

def create
@link = current_user.build(link_params)

……..

end

Changing the definition to current_user.links.build makes sure that once a user created a link, it belongs to him.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s