Reputation: 5343
For some reason the edit action won't render i get this error and is using show action instead of edit but the same form works for the render :new action
render :edit
ActionController::UrlGenerationError in Admin::Blog::Posts#update
No route matches {:action=>"show", :controller=>"admin/blog/posts", :id=>""} missing required keys: [:id]
def edit
@post = Post.find_by_permalink(params[:id])
end
def update
@post = Post.find_by_permalink(params[:id])
if params[:publish]
@post.publish
elsif params[:draft]
@post.draft
end
if params[:preview]
if @post.published?
@post.draft
end
if @post.update(blog_post_params)
flash[:success] = "some text "
redirect_to blog_post_url(@post)
else
render :edit
end
end
if @post.update(blog_post_params)
flash[:success] = "Post was successfully updated."
redirect_to edit_admin_blog_post_url(@post)
else
render :edit
end
end
form
<%= form_for [:admin,:blog, @post] do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="large-12 columns">
<div class="field panel">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field panel">
<%= f.label :description %><br>
<%= f.text_field :description %>
</div>
<div class="actions panel text-right">
<% if @post.published? %>
<%= f.submit "Save Changes",name: "publish", class: "tiny button radius success" %>
<% else %>
<%= f.submit "Publish",name: "publish", class: "tiny button radius success" %>
<% end %>
<%= f.submit 'Mark as Draft', name: "draft", class: "tiny button radius " %>
<% if @post.created_at %>
<%= f.submit 'Preview', name: "preview", class: "tiny button radius warning" %>
<% end %>
<%= link_to 'Back', admin_blog_posts_path, class: "tiny button radius secondary" %>
</div>
<div class="field panel">
<%= f.label :body %><br>
<%= f.cktext_area :body, :height => '800px', :id => 'sometext' %>
</div>
</div>
<% end %>
relevant routes
namespace :admin do
namespace :blog do
get '', to: 'welcome#index', as: '/'
resources :posts
end
end
post model
class Post < ActiveRecord::Base
has_many :tags
has_many :comments
before_validation :generate_permalink
validates :permalink, uniqueness: true
validates :title, presence: true
validates :description, presence: true
def generate_permalink
self.permalink = title.parameterize
end
def to_param
permalink
end
end
Upvotes: 0
Views: 651
Reputation: 4015
I guess i know why you get this error.
In the edit
action you use Post.find_by_permalink(params[:id])
to find your post, which returns nil
if nothing was found. And since you may change the title
attribute, your permalink is updated (i guess), and your post is not found. The controller still renders the action, with nil
@post
, and cannot generate the url for the form.
Try using Post.find_by_permalink!(params[:id])
instead, and you will get a 404.
I would actually suggest you to use regular find
in the admin area, since the permalink might change.
Upvotes: 1