Ell*_*iot 3 controller ruby-on-rails
我认为这是一个艰难的问题.我有一个评论控制器,我想用于我的所有其他控制器:如书籍,标题等.
问题是,评论中的创建操作是:
def create
@book = Book.find(params[:book_id])
@comment = @book.comments.create!(params[:comment])
respond_to do |format|
format.html {redirect_to @book}
format.js
end
Run Code Online (Sandbox Code Playgroud)
结束
那么,如果它明显使用书籍属性,我如何使用动作和评论控制器作为标题?
我假设您在评论上设置了多态关联,因此它可以属于许多不同类型的模型?看看这个Railscasts剧集,它向您展示如何设置它与控制器动作.这是代码的关键部分.
# comments_controller
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
if @comment.save
flash[:notice] = "Successfully created comment."
redirect_to :id => nil
else
render :action => 'new'
end
end
private
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
# routes.rb
map.resources :books, :has_many => :comments
map.resources :titles, :has_many => :comments
map.resources :articles, :has_many => :comments
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
923 次 |
| 最近记录: |