轨。视图中的错误

时间:2012-04-12 12:23:12

标签: ruby-on-rails devise

我有PostController,我使用了decent_exposure gem。

#posts_controller.rb
class PostsController < ApplicationController
  expose(:posts) { Post.all }
  expose(:post) do 
   Post.find(params[:id]) || Post.new
  end

  def create
    post = current_user.posts.new(params[:post])
    if post.save
      redirect_to post, notice: 'Post was successfully created.' 
    else
      render action: :new 
    end
  end

  def update
   if post.update_attributes(params[:post])
    redirect_to post, notice: 'Post was successfully updated.' 
   else
    render action: "edit" 
   end
  end

  def destroy
   post.destroy
   redirect_to posts_url, notice: "Post was deleted." 
  end
end

模特邮报。

class Post < ActiveRecord::Base
  extend FriendlyId 
  friendly_id :title, use: :slugged

  acts_as_taggable_on :tags


  belongs_to :user
  has_many :comments, :dependent => :destroy  

  attr_accessible :title, :content, :tag_list 
  validates :title, :content, :user_id, :presence => true 
  validates :tag_list, :length => {:minimum => 1 ,:maximum => 6 } 
end

和_form.html.erb

<%= form_for(post) do |f| %>
 <% if post.errors.any? %>
  <div id="error_explanation">
   <h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2>

  <ul>
  <% post.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
  </ul>
</div>
<% end %>
#Fields.
<div class="actions">
  <%= f.submit %>
</div>
   

但是为什么当我尝试创建新帖子时,我收到错误?

Couldn't find Post without an ID

为什么?

2 个答案:

答案 0 :(得分:1)

尝试替换:

Post.find(params[:id]) || Post.new

使用:

Post.find_by_id(params[:id]) || Post.new

答案 1 :(得分:0)

常见的模式是检查是否提供了ID。

您通常也应该使用posts.findposts.build而不是Post.findPost.new

expose(:post) { (id = params[:id]) ? posts.find(id) : posts.build }