0

I’m wanting to create an Asset from an Organisation Show page. I need the Organisation ID to be passed to the Asset for creation.

# ../models/organisation.rb
has_many :assets

# ../models/asset.rb
belongs_to :organisation

I have a button to create an asset, which is passing the organisation.id in the URL params.

# ../views/organisations/show.html.erb    
<%= link_to 'New Asset', new_asset_path(:organisation_id => @organisation.id) %>

I'm able to access the organisation_id value in the ../views/assets/new view, however, when I submit the form I'm receiving a “Method not allowed” error.

# ../controllers/assets_controller.rb

def create
    @asset = Asset.new(params[:organisation_id])
    ...
end

Q1: Why am I getting this error:

Q2: Is there another way to pass the organisation_id through to the Asset new page? I.e. not in the URL.

Q3: If I can only pass the ID through the URL, Is there a way to stop a user tampering with it? I.e. changing the Org ID to something else and saving the asset to another organisation.

Q4: Would nested resources help in this instance?

Rails 5.0.0.1, Ruby 2.3.1

  • You need to tell `Asset.new` what the organisation_id param is *for* eg: `@asset = Asset.new(:organisation_id => params[:organisation_id])` otherwise you're just passing it a random number and it's going "wtf is this?" :D (well, technically it's looking for a version of the `new` method that takes a single argument that isn't a hash... which it can't find, then telling you that method doesn't exist... but same diff). ;) – Taryn East Sep 20 '16 at 03:25
  • Makes sense - thanks. –  Sep 20 '16 at 05:00
  • made into an answer :) – Taryn East Sep 20 '16 at 05:29

3 Answers3

0

I think you should use like:

  def create
    @asset = Asset.new(organisation_id:params[:organisation_id])
  end
Kaushlendra Tomar
  • 1,364
  • 8
  • 15
0

Q.1 - The error is due to the name of the model - "Assets". This is a reserved word in Rails.

It can be fixed by moving the asset pipeline to another mount point. For example:

# config/initializers/assets.rb

Rails.application.config.assets.prefix = '/pipeline_assets'

As mentioned here:

405 Error when trying to POST a file in rails

Rails 4 Method Not Allowed after Upgrading from Rails 3

Community
  • 1
  • 1
0

You need to tell Asset.new what the organisation_id param is for eg:

@asset = Asset.new(:organisation_id => params[:organisation_id])

otherwise you're just passing it a random number and it's going "wtf is this?" :D

(well, technically it's looking for a version of the new method that takes a single argument that isn't a hash... which it can't find, then telling you that method doesn't exist... but same diff). ;)

Taryn East
  • 26,180
  • 8
  • 82
  • 101