繼RoR Turorial之後,我正在構建基本書籤應用程序。如何在RoR中呈現字符串屬性作爲URL
我有兩個型號,topic
和bookmark
。
書籤有一個url
屬性。 url
屬性在我的topics#show
上呈現正常,但是顯示爲純文本。當我試圖將其渲染爲鏈接時,它不會正確鏈接到網址。
如何將其渲染爲超鏈接?
我已經試過這
<%= @topic.bookmarks.each do |bookmark| %>
<a href="#{bookmark.url}">bookmark.url</a>
<% end %>
但顯然不看的權利。我是否插入了正確的方法?
或者有一個鐵軌助手的方法,會做的伎倆?
這裏是我的文件
主題控制器
類TopicsController < 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
末
我的書籤控制器
類BookmarksController < 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} %>
拋出了一個錯誤'無法與 'ID' 找到主題= ....' – deventhusiast 2015-02-09 15:51:30
這是一個單獨的問題。假設你有一個帶有有效URL的書籤對象,'''link_to'''應該可以正常工作。 – Adib 2015-02-09 15:53:35
我使用<%= link_to bookmark.url,bookmark.url%>,因爲其他明智的我所有的鏈接或上面的代碼的情況下,一個按鈕將使用「名稱」而不是鏈接名稱呈現。 – deventhusiast 2015-02-09 17:06:27