2011-07-15 161 views
0

我有一個rails應用程序,我想將附件添加到資產,所以我想能夠撥打http://localhost:3000/attachments/:asset_id/new,以便它會自動帶入資產ID。我不知道如何在視圖中進行配置,但我認爲我一次做過一次。那麼我怎麼能完成這個任務呢?rails從URL獲取參數

據我已經這麼遠,我相信這是正確的是添加以下行的routes.rb:

match 'attachments/:asset_id/new'=>'attachments#new' 

注:這是Rails 3中的應用。

+0

由於我無法發佈答案,因此我在此發佈了答案:http://pessetto.com/question2answer/index.php?qa=30&qa_1=how-do-i-get-the-parameter-from -url-in-rails-3 –

回答

2

你能做到這一點的RESTful方式就像這樣:

resources :assets do 
    resources :attachments # this would give you localhost:3000/assets/:asset_id/attachments/new for your #new action 
end 

或非RESTful方式:

match 'attachments/:asset_id/new'=>'attachments#new', :as => "new_attachments_asset" 

我建議你使用前)爲寧靜的例子,您的附件#新行動可能是:

def new 
    @asset = Asset.find(params[:asset_id]) 
    @attachment = @asset.attachments.build # assuming a has_many/belongs_to association 
end 
+0

一旦集成到實際系統中,我會這樣做,我假設新命令需要:@attachment = Attachment.new(:asset_id => params [:asset_id])在其中獲取Asset_Id到視圖的隱藏字段中。 –

+0

這取決於您的表單的結構。在使用表單助手的寧靜示例中,通常會有類似於Attachment.new(params [:attachment])的內容;你需要自己設定每個屬性。另外請記住,如果您想在Attachment.new – emrass

+0

上指定屬性值,您的屬性需要可用於批量分配(模型中的attr_accessible)。對不起,誤解了您的問題。在NEW操作中,您將擁有@asset = Asset.find(params [:asset_id])&& @ asset.attachments.build(或者has_one/belongs_to關聯的情況:@ asset.build_attachment) – emrass