I have a one-to-many association between 2 resources: Discovery and Matter
class Discovery < ActiveRecord::Base
belongs_to :matter
end
class Matter < ActiveRecord::Base
has_many :discoveries
end
My routes file has this:
resources :matters do
resources :discoveries
end
My migration files look like:
class CreateDiscoveries < ActiveRecord::Migration
def change
create_table :discoveries do |t|
t.string :aws_url
t.string :upload_file_path
t.attachment :upload
t.integer :matter_id
t.string :direct_upload_url
t.boolean :processed
t.timestamps
end
end
end
class AddMatterIdToDiscoveries < ActiveRecord::Migration
def change
add_index :discoveries, :matter_id
add_index :discoveries, :processed
end
end
discoveries_controller.rb
def create
@matter = Matter.find(params[:matter_id])
if(params[:url])
@discovery = Discovery.new
render "new" and return
end
if(params[:discovery][:upload_file_path])
@discovery = Discovery.new(discovery_params)
respond_to do |format|
if @discovery.save
@discovery.matter = current_user.matters.find(params[:matter_id])
format.html { render action: :show, notice: 'Discovery was successfully created.' } # matter_url(@discovery.matter_id)
format.json { render action: 'show', status: :created, location: @discovery }
else
format.html { render action: 'new' }
format.json { render json: @discovery.errors, status: :unprocessable_entity }
end
# redirect_to new_document and return
end
else
@discovery = Discovery.new
render action: 'new', notice: "No file"
end
end
When I create a new discovery in the matters model matters/3/discoveries/new
the discovery gets created, but in the console, I thought I should be able to access Discovery.last.matter
, but instead I get the error NoMethodError: undefined method 'matter' for #<Discovery:0x0000000495dc98>
How would I go about showing the matter that the discovery belongs to? Thanks
Call reload!
in the console after changing your models (schema changes, running migrations, adding methods).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.