My problem is connected with my previous problem. It was solved by using nested routing. But there was different idea without using nested resources. I tried it as an exercise. But when I submit data, ActiveRecord::RecordNotFound in SentencesController#create shows up.
Rails.application.routes.draw do
root 'stories#index'
get 'stories/show'
get 'stories/new'
post 'stories/:story_id', to: 'sentences#create'
resources :stories
resources :sentences, only: [:create]
end
shared/_sentence_form.html.erb is part of story/show_form.html.erb
<%= form_for(@sentence) do |f| %>
<%= hidden_field_tag :story_id, value: @story.id %>
<%= f.text_area :content, placeholder: "Compose new sentence..." %>
<%= f.submit "Save"%>
<% end %>
SentencesController
class SentencesController < ApplicationController
before_action :sentence_params
before_action :find_story
def create
@sentence = find_story.sentences.build(sentence_params)
if @sentence.save
flash[:success] = "You wrote the continuation!"
redirect_to root_url
else
flash[:danger] = "I did not save your words!"
redirect_to "#"
end
end
private
def sentence_params
params.permit(:content, :story_id)
end
def find_story
@story = Story.find(params[:story_id])
end
end
and model:
class Sentence < ApplicationRecord
belongs_to :story
validates :story_id, presence: true
validates :content, presence: true, length: { maximum: 150 }
end
I tried many combinations in controller and view. When I put some information in the text_area and click submit they don't save.
hidden_field_tag :story_id, value: @story.idshould be this:hidden_field_tag :story_id, @story.id@maxAs I wrote this is an exercise. I'm Rails beginner and I'm experimenting a bit to get along with Ruby (on Rails). Thanks for advice to keep REST designing.