【发布时间】:2013-11-15 16:12:24
【问题描述】:
请原谅我的无知,但我对 RoR 很陌生。我正在开发一个项目,用户可以复制帖子以编辑此“克隆版本”并保存它(当然,使用新的帖子 ID)。
首先我尝试使用here 描述的Amoeba gem,但我失败了。
然后我想我找到了一个更好的解决方案 - Duplicating a record in Rails 3 - 但是当我集成建议的代码时,我收到以下错误:
帖子中的 NoMethodError#show #
的未定义方法 `clone_post_path'现在研究和修补了几个小时,我真的很感激任何帮助!
我正在使用 Rails 3.2.13。
在我的 posts_controller 中,我有以下代码:
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @post }
end
end
def new
@post = current_user.posts.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @post }
end
end
def clone
@post = current_user.posts.find(params[:id]) # find original object
@post = current_user.posts.new(@post.attributes) # initialize duplicate (not saved)
render :new # render same view as "new", but with @post attributes already filled in
end
def create
@post = current_user.posts.new(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render json: @post, status: :created, location: @post }
else
format.html { render action: "new" }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
这是 post.rb 模型:
class Post < ActiveRecord::Base
attr_accessible :content, :title, :videos, :link, :description
validates :title, presence: true
belongs_to :user
end
在显示视图中我称之为:
<%= link_to 'Create a clone', clone_post_path(@post) %>
我做错了什么? 非常感谢您的帮助!
更新: 添加
resources :posts do
get 'clone', on: :member
end
到路由文件工作。
这里是路由文件:
Tt::Application.routes.draw do
devise_for :users
get 'about' => 'pages#about'
resources :posts
root :to => 'pages#home'
post 'attachments' => 'images#create'
resources :posts do
get 'clone', on: :member
end
结束
不幸的是,发生了一个新的错误:
ActiveModel::MassAssignmentSecurity::PostsController#clone 中的错误 无法批量分配受保护的属性:id、created_at、updated_at、image_file_name、image_content_type、image_file_size、image_updated_at、file、user_id
【问题讨论】:
-
能否请您也发布与 Post 控制器有关的路线?我猜您没有将 get :clone, on: :member 添加到您的帖子路线中。
-
谢谢大卫!见上文。
-
@davidfurber 您的“on:member”提示有效!往上看。成就了我的一天!不幸的是,现在我有一个新错误:ActiveModel::MassAssignmentSecurity::Error in PostsController#clone Can't mass-assign protected attributes: id, created_at, updated_at, image_file_name, image_content_type, image_file_size, image_updated_at, file, user_id
-
查看这篇文章以了解您的批量分配问题,它可能会有所帮助。 stackoverflow.com/questions/10574957/…
标签: ruby-on-rails ruby-on-rails-3 clone duplicate-data