在我正在构建基本书签应用程序的RoR turorial之后。
我有两个模型,topic
和bookmark
。
书签具有url
属性。 url
属性在我的topics#show
上正常呈现,但是作为纯文本。当我尝试将其渲染为链接时,它没有正确链接到URL。
如何将其渲染为超链接?
我试过这个
<%= @topic.bookmarks.each do |bookmark| %>
<a href="#{bookmark.url}">bookmark.url</a>
<% end %>
但显然这看起来不对。我是否以正确的方式进行插值?
另外还有一个可以解决问题的rails辅助方法吗?
这是我的文件
主题控制器
类TopicsController&lt; ApplicationController中
def index
@topics = Topic.all
end
def new
@topic = Topic.new
end
def show
@topic = Topic.find(params[:id])
end
def create
@topic = Topic.new(params.require(:topic).permit(:name))
if @topic.save
redirect_to @topic
else
render :new
end
end
端
我的书签控制器
class BookmarksController&lt; ApplicationController中
def create
@topic = Topic.find(params[:topic_id])
@bookmarks = @topic.bookmarks
@bookmark = @topic.bookmarks.build(params.require(:bookmark).permit(:url, :topic_id))
@bookmark.topic = @topic
@new_bookmark = Bookmark.new
if @bookmark.save
flash[:notice] = "Bookmark was saved"
redirect_to @topic
else
flash[:error] = "There was an error, please try again later"
redirect_to @topic
end
end
def destroy
@topic = Topic.find(params[:topic_id])
@bookmark = Bookmark.find(params[:id])
@bookmark.topic = @topic
if @bookmark.destroy
flash[:notice] = "Bookmark was destroyed successfully"
redirect_to [@topic]
else
flash[:error] = "There was an error, please try again later"
end
end
端
这些是我的迁移文件
class CreateTopics < ActiveRecord::Migration
def change
create_table :topics do |t|
t.string :name
t.timestamps
end
end
end
class CreateBookmarks < ActiveRecord::Migration
def change
create_table :bookmarks do |t|
t.string :url
t.references :topic, index: true
t.timestamps
end
end
end
这是我的路线档案
Rails.application.routes.draw do
resources :topics do
resources :bookmarks, only: [:destroy, :create]
end
get 'about' => 'welcome#about'
root to: 'welcome#index'
end
书签形式部分显示在topics#show
<%= form_for [@topic, @topic.bookmarks.new] do |f| %>
<div class="col-md-5">
<div class="form-group">
<%= f.text_field :url, placeholder: "Enter bookmark url", class: 'form-control' %>
</div>
<%= f.submit "save", class: 'form-control' %>
</div>
<% end %>
topics#show
中的添加了此行以呈现部分
<%= render partial: 'bookmarks/form', locals: { topic: @topic, bookmark: @bookmark} %>
答案 0 :(得分:3)
您是否尝试过使用帮助器link_to
?
<%= link_to 'name', bookmark.url, class: 'btn btn-default' %>
答案 1 :(得分:1)
ERB不会插入字符串,除非它们位于ERB块内(<%
... %>
)。
即,在您的情况下,以下内容可行:
<a href="<%= bookmark.url %>">bookmark.url</a>
更清洁的解决方案是使用另一个答案中提到的link_to
。我只是认为理解为什么原始解决方案不起作用很重要。
答案 2 :(得分:1)
您可以使用link_to
辅助方法:
<%= @topic.bookmarks.each do |bookmark| %>
<%= link_to bookmark.url, bookmark.url %>
<% end %>
更多信息here