Ruby on Rails不会在没有id

时间:2015-11-10 15:19:34

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

由于某种原因,编辑操作不会呈现我收到此错误并使用show动作而不是编辑但相同的表单适用于渲染:新操作

  • 不关注params [:preview],我说的是最后一个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_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 %>

相关路线

namespace :admin do
     namespace :blog do
          get '', to: 'welcome#index', as: '/'
          resources :posts
     end
end

发布模型

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

1 个答案:

答案 0 :(得分:1)

我想我知道你为什么会收到这个错误。

edit操作中,您使用Post.find_by_permalink(params[:id])查找您的帖子,如果找不到任何内容,则返回nil。由于您可以更改title属性,因此您的永久链接会更新(我猜),并且找不到您的帖子。控制器仍然使用nil @post呈现操作,并且无法生成表单的网址。

请尝试使用Post.find_by_permalink!(params[:id]),然后您将获得404。

我实际上建议您在管理区域中使用常规find,因为永久链接可能会发生变化。