简体   繁体   中英

Generating a URL from user-submitted input in Ruby on Rails

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!

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM