0
我有一個線在我的routes.rb映射我的相冊樣板作爲一種資源:與DataMapper的和Rails的重定向
map.resources :albums
然而,在Rails的替代ActiveRecord的使用DataMapper的,爲什麼會這樣一行:
format.html { redirect_to(@album) }
原因重定向到:
albums/%23<Album:0x72d452c>
代替:
albums/1
如果需要進一步的情況下,從控制我的全部create方法是列在這裏:
def create
@album = Album.new(params[:album])
respond_to do |format|
if @album.save
flash[:notice] = 'Album was successfully created.'
format.html { redirect_to(@album) }
format.xml { render :xml => @album, :status => :created, :location => @album }
else
format.html { render :action => "new" }
format.xml { render :xml => @album.errors, :status => :unprocessable_entity }
end
end
end
由於是慣例,該方法被調用從我的「新表單提交的結果「方法在new.html.erb:
<h1>New album</h1>
<% form_for(@album) do |f| %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :description %><br />
<%= f.text_field :description %>
</p>
<p>
<%= f.label :genre %><br />
<%= f.text_field :genre %>
</p>
<p>
<%= f.label :country %><br />
<%= f.text_field :country %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
<%= link_to 'Back', albums_path %>
哇。這工作。但爲什麼它工作?在我的例子中,什麼是「%23 <專輯:0x72d452c>」?這不是對相冊對象的某種原始表示嗎?因此,通過創建to_param方法,如何確保表示對象的id而不是對象表示?是否因爲有一個默認的to_param方法將該對象表示爲此代碼:「%23」?驚人。我很想知道你是怎麼想出來的。你一定非常瞭解Rails的內部。 –
Baker
2009-06-08 04:55:11
內臟必須做一個respond_to?在調用to_param之前檢查,因爲路由方法也接受整數,數組和散列。 %23 <專輯:0x72d452c>是#<專輯:0x72d452c>的網址編碼,這或多或少是Ruby通過inspect方法公開對象的方式,除非像ActiveRecord這樣的對象重寫了該方法。由於你的DM模型不是一個AR或一個數組或哈希,你只需要在對象上調用to_s,可能是作爲字符串插值的一部分。 我有機會搞砸我發送到路由方法的對象,所以我之前就看到過這個問題。 – austinfromboston 2009-06-08 05:10:54
感謝您的解釋。 – Baker 2009-06-08 05:24:52