To learn Rails, I'm working on a simple calendar app. To get started, I created two scaffolds and the proper associations/routes:
- calendars
- content_items
app/models/calendar.rb
class Calendar < ActiveRecord::Base
has_many :content_items
end
app/models/content_item.rb
class ContentItem < ActiveRecord::Base
belongs_to :calendar
end
routes.rb
resources :calendars do
resources :content_items
end
controllers/content_items_controller.rb
def create
@content_item = ContentItem.new(content_item_params)
@calendar = Calendar.find(params[:calendar_id] )
respond_to do |format|
if @content_item.save
format.html { redirect_to calendar_content_item_path(@calendar,@content_item), notice: 'Content item was successfully created.' }
format.json { render :show, status: :created, location: @content_item }
else
format.html { render :new }
format.json { render json: @content_item.errors, status: :unprocessable_entity }
end
end
end
When I created the nested routes, I began to run into errors when trying to create new content_items. Whenever I submit the form, I get this error:
NoMethodError in ContentItems#create
undefined method `content_items_path'
The error is coming from: views/content_items/index.html.erb
<%= form_for [@calendar, @content_item] do |f| %>
UPDATE Using the code posted below by @Gaurav GuptA fixed the form issue, but led to a new errror. Whenever I visit /calendars/1/content_items, I recieve an error - but only after creating an entry. With an empty database, it works fine.
ActionController::UrlGenerationError No route matches {:action=>"show", :calendar_id=>#, :controller=>"content_items", :format=>nil, :id=>nil} missing required keys: [:id]
I believe this is because the content_item is being saved without a calendar_id. How do I set the content_item to save with the calendar_id it belongs to?
UPDATE 2 It now saves with a calendar_id, but when an item is saved, the links for edit/shpw/destroy throw errors.
No route matches {:action=>"show", :calendar_id=>#<ContentItem id: 1, , content_type: "Test", content_text: "Tetst\r\n", calendar_id: 1, created_at: "2015-05-26 07:06:42", updated_at: "2015-05-26 07:06:42", content_image_file_name: nil, content_image_content_type: nil, content_image_file_size: nil, content_image_updated_at: nil>, :controller=>"content_items", :format=>nil, :id=>nil} missing required keys: [:id]
It highlights this part of the file:
<td><%= link_to 'Show', calendar_content_item_path(content_item) %></td>
GitHub link: https://github.com/JeremyEnglert/baked