Reputation: 69
In my rails app, I have added a string that users can add the link to there facebook profile, it's a simple text field, but in the view I want them to have a link.
For example, if the user adds www.facebook.com/example I want it to appear as a link in the views for that I have tried the link_to
approch but instead of pointing a link to the users profile it just refresh the page.
This is what I tried
<%= link_to(@user.fblink) %>
migration
class AddFblinkToUsers < ActiveRecord::Migration
def change
add_column :users, :fblink, :string
end
end
user controller prams
def user_params
params.require(:user).permit(:description, :avatar, :location, :fblink, :twlink, :ytlink, :username)
end
Upvotes: 2
Views: 1054
Reputation: 7777
If your form is inserted data properly then, You can work on defining a helper class for link like
#=> helpers/application_helper.rb
def fb_link(user_fb)
link_to "Facebook", "#{url_with_protocol(user_fb)}", class: "your-class", target: "new"
end
#=> url helper
def url_with_protocol(url)
/^http/.match(url) ? url : "http://#{url}"
end
Then from view
= fb_link(@user.fblink)
Or you can work like this
= link_to "Facebook", "#{url_with_protocol(@user.fblink)}", class: "your-class", target: "new"
Hope it helps
Upvotes: 2
Reputation: 651
Try <%= link_to 'Facebook', @user.fblink %>
The first parameter of link_to
method will display the value of the link. In this case it is Facebook
. The second parameter is the url_path
. When user click to the Facebook
link it will go the url_path
. In this case it is @user.fblink
.
Upvotes: 0
Reputation: 6531
it will not work as link untill unless its not been saved as http
,
for example if you want Facebook link to work its should be saved in db as https://www.facebook.com/example
so here for this you need a jquery form validation on your form input field:
and after that in your view page simply you can use it like
my link <%=@[email protected]%>
do not use link_to
or any rails view helper here as its complete link is been alredy saved in database.
<script>
$( "#myform" ).validate({
rules: {
field: {
required: true,
url: true
}
},
message: {
field:{ required: 'fb link can't be blank!', url: 'Please enter valid url'}
}
});
</script>
Upvotes: 1