Reputation: 232
I'm trying to use PaperClip inside my application.
I have 3 models: menu, user and pub. I would like the user to be able to add a menu, which is a pdf file, for a pub. So when I upload the pdf file, I would like to have a column in the menu model with the pub id.
menu.rb
has_attached_file :document
validates_attachment :document, :content_type => {:content_type => %w(application/pdf)}
new.html.erb
<div class="page-header"><h1>Upload Menu</h1></div>
<%= form_for ([@pub, @menu]), html: { multipart: true } do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="form-group">
<%= f.label :title %>
<%= text_field :title, class: 'form-control' %>
<%= f.label :document %>
<%= f.file_field :document, class: 'form-control' %>
<%= f.submit 'Upload Menu', class: 'btn btn-primary' %>
</div>
<% end %>
routes.rb
resources: pubs do
resources :menus
end
menus_controller.rb
class MenusController < ApplicationController
def index
@menus = Menu.order('created_at')
end
def new
@menu = Menu.new
end
def create
@pub = Pub.find(params[:pub_id])
input = menu_params.merge(pub: @pub)
@menu = current_user.menus.build(input)
if @menu.save
flash[:success] = "Successfully added new menu!"
redirect_to root_path
else
flash[:alert] = "Error adding new menu!"
render :new
end
end
private
def menu_params
params.require(:menu).permit(:title, :document)
end
end
Button for the new page to upload a file
<%= link_to "Upload menu", new_pub_menu_path(@pub), class: 'btn btn-primary' %>
So when I click the button, I get to the new_pub_menu_path(@pub) generated link, but I have an error ..
error
ActionView::Template::Error (undefined method `menus_path' for #<#<Class:0x007f652ce54550>:0x007f652c90c9a8>
Did you mean? user_path):
1:
2: <%= form_for ([@pub, @menu]), html: { multipart: true } do |f| %>
3: <%= render 'shared/error_messages', object: f.object %>
4:
5: <div class="form-group">
What should I do? I tried to use the nested routes so to have in the url the id pub, but when the new.html.file is rendered it gives me that error. I don't know what method menus_path is. Thanks!
Upvotes: 0
Views: 879
Reputation: 33552
undefined method `menus_path' for
You didn't defined @pub
in new
method of menus_controller
, so @pub
is nil
in new.html.erb
, so is the error. Define it to resolve the issue.
def new
@menu = Menu.new
@pub = Pub.find(params[:pub_id])
end
Upvotes: 1