Travis Pessetto
Travis Pessetto

Reputation: 3298

rails Getting the parameter from the URL

I have a rails application that I want to add attachments to assets, so I want to be able to call http://localhost:3000/attachments/:asset_id/new so that that it will automatically bring in the asset id. I don't know how to configure this in views, though I think I did it once-upon-a-time. So how could I accomplish this task?

As far as I have got so far, and I believe this is correct is adding the following line to routes.rb:

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

Note: This is a Rails 3 Application.

Upvotes: 0

Views: 109

Answers (2)

emrass
emrass

Reputation: 6444

You could do it the RESTful way like so:

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

or the non-RESTful way:

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

I'd recommend the former ;) For the restful example, your Attachment#new action could be:

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

Upvotes: 2

Related Questions