0

我有 PostController,我使用了体面的曝光 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

为什么?

4

2 回答 2

1

尝试替换:

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

和:

Post.find_by_id(params[:id]) || Post.new
于 2012-04-12T12:47:13.993 回答
0

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

您通常还应该使用posts.findandposts.build而不是Post.findand Post.new

expose(:post) { (id = params[:id]) ? posts.find(id) : posts.build }
于 2012-04-12T13:03:45.587 回答