0

I want users to submit a title and a url link in a form. Then I want to render that title as a link, which contains the url. So in the form below the title would contain "Stack Overflow" and the content would be "www.stackoverflow.com"

<%= form_for @post, url: user_posts_path(@user) do |f| %>
<%= f.text_field :title, :class => 'form-control', :type => "title", :placeholder => "title" %>
<%= f.text_field :content, :class => 'form-control', :type => "text", :placeholder => "URL" %>
<%= f.submit "Submit" %>
<% end %>

I'm still confused by some aspects of Rails and there doesn't seem to be anything clear in the docs for what I am asking. The code below is how I have things routed now, which works by taking the user to the show route for the post.

<%= link_to post.title, user_post_path(post.user_id, post.id) %>

What I want instead is to have something like this

<%= link_to post.title, url(post.content)%>

Instead of user_post_path it would the actual content of the post, in this case post.content, which would be "www.stackoverflow.com" I have no idea if this is even possible as I am new to RoR but any suggestions for solving this problem would be greatly appreciated thanks!

2 Answers 2

2

link_to will accept a simple string as href. I'll recommend using URI.parse though, to make sure the text is a valid URL.

<%= link_to post.title, URI.parse(post.content) %>

You should also make sure that the text saved in the content attribute is only containing an URL. You could achieve this using JS in the field, in your controller, or a in a model callback, using the URI.extract method before saving the record.

Sign up to request clarification or add additional context in comments.

Comments

0

You can pass query parameters to your link directly like this:

link_to "Ruby on Rails search", controller: "searches", query: "ruby on rails"

<a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.