2

私はこのhttp://railscasts.com/episodes/154-polymorphic-association-revisedの投稿を読んで、そのまま実装しました。しかし、このチュートリアルにも編集および削除機能を追加したいと思います。私はcomments_controller.rbはこのようなものです

class CommentsController < ApplicationController
  before_filter :load_commentable

  def index
    @comments = @commentable.comments
  end

  def new
    @comment = @commentable.comments.new
  end

  def create
    @comment = @commentable.comments.new(params[:comment])
    if @comment.save
      redirect_to @commentable, notice: "Comment created."
    else
      render :new
    end
  end

private

  def load_commentable
    resource, id = request.path.split('/')[1, 2]
    @commentable = resource.singularize.classify.constantize.find(id)
  end

  # def load_commentable
  #   klass = [Article, Photo, Event].detect { |c| params["#{c.name.underscore}_id"] }
  #   @commentable = klass.find(params["#{klass.name.underscore}_id"])
  # end
end

与えられた私の _comments.html.erb はこのようなものです

<div id="comments">
<% @comments.each do |comment| %>
  <div class="comment">
    <%= simple_format comment.content %>
  </div>
<% end %>
</div>

私のルートはこのようなものです

Blog::Application.routes.draw do
  resources :articles do
    resources :comments
  end

  resources :photos do
    resources :comments
  end

  resources :events do
    resources :comments
  end
  resources :comments

  root to: 'articles#index'
end

私のレーキルートはこのようなものです

 article_comment GET    /articles/:article_id/comments/:id(.:format)      comments#show
                     PUT    /articles/:article_id/comments/:id(.:format)      comments#update
                     DELETE /articles/:article_id/comments/:id(.:format)      comments#destroy
            articles GET    /articles(.:format)                               articles#index
                     POST   /articles(.:format)                               articles#create
         new_article GET    /articles/new(.:format)                           articles#new
        edit_article GET    /articles/:id/edit(.:format)                      articles#edit
             article GET    /articles/:id(.:format)                           articles#show
                     PUT    /articles/:id(.:format)                           articles#update
                     DELETE /articles/:id(.:format)                           articles#destroy
      photo_comments GET    /photos/:photo_id/comments(.:format)              comments#index
                     POST   /photos/:photo_id/comments(.:format)              comments#create
   new_photo_comment GET    /photos/:photo_id/comments/new(.:format)          comments#new
  edit_photo_comment GET    /photos/:photo_id/comments/:id/edit(.:format)     comments#edit
       photo_comment GET    /photos/:photo_id/comments/:id(.:format)          comments#show
                     PUT    /photos/:photo_id/comments/:id(.:format)          comments#update
                     DELETE /photos/:photo_id/comments/:id(.:format)          comments#destroy
              photos GET    /photos(.:format)                                 photos#index
                     POST   /photos(.:format)                                 photos#create
           new_photo GET    /photos/new(.:format)                             photos#new
          edit_photo GET    /photos/:id/edit(.:format)                        photos#edit
               photo GET    /photos/:id(.:format)                             photos#show
                     PUT    /photos/:id(.:format)                             photos#update
                     DELETE /photos/:id(.:format)                             photos#destroy
      event_comments GET    /events/:event_id/comments(.:format)              comments#index
                     POST   /events/:event_id/comments(.:format)              comments#create
   new_event_comment GET    /events/:event_id/comments/new(.:format)          comments#new
  edit_event_comment GET    /events/:event_id/comments/:id/edit(.:format)     comments#edit
       event_comment GET    /events/:event_id/comments/:id(.:format)          comments#show
                     PUT    /events/:event_id/comments/:id(.:format)          comments#update
                     DELETE /events/:event_id/comments/:id(.:format)          comments#destroy
              events GET    /events(.:format)                                 events#index
                     POST   /events(.:format)                                 events#create
           new_event GET    /events/new(.:format)                             events#new
          edit_event GET    /events/:id/edit(.:format)                        events#edit
               event GET    /events/:id(.:format)                             events#show
                     PUT    /events/:id(.:format)                             events#update
                     DELETE /events/:id(.:format)                             events#destroy
            comments GET    /comments(.:format)                               comments#index
                     POST   /comments(.:format)                               comments#create
         new_comment GET    /comments/new(.:format)                           comments#new
        edit_comment GET    /comments/:id/edit(.:format)                      comments#edit
             comment GET    /comments/:id(.:format)                           comments#show
                     PUT    /comments/:id(.:format)                           comments#update
                     DELETE /comments/:id(.:format)                           comments#destroy
                root        /                                                 articles#index
4

3 に答える 3

1

そのようです....?これは、ルートが「コメント可能な」ルートの下の:Editおよび:updateアクションに対してネストされていることを前提としています。

  def edit
    @comment = @commentable.comments.find(params[:id])
  end

  def create
    @comment = @commentable.comments.find(params[:id])
    if @comment.update_attributes(params[:comment])
      redirect_to @commentable, notice: "Comment updated."
    else
      render :edit
    end
  end

編集内容は次のようになります。

<%= link_to 'Edit', [:edit, @comment.commentable, @comment] %>

ただし...何らかの認証や承認が必要になります。

于 2013-01-29T08:00:00.957 に答える
0

今はこれを調べる時間があまりありませんが、あなたのツイートに応えて、テストアプリで使用していたコードを投稿しています。ここではHAMLを使用しています。

私の見解で編集または削除リンクを要求するとき、私はこの部分を使用しました:

- @category.photos.each do |photo|
    = image_tag photo.image_url(:thumb)
    %figcaption
        = link_to "Change", [:edit, @category, photo]

        = link_to "Delete", [@category, photo], :method => :delete
= link_to "New photo", [:new, @category, :photo]

私の写真コントローラー:

class PhotosController < ApplicationController
  def create
    @category = Category.find(params[:category_id])
    @photo = @category.photos.create!(params[:photo])
    redirect_to @category, :notice => "Photo created."
  end

  def edit
    @category = Category.find(params[:category_id])
    @photos = @category.photos
    @photo = @photos.find(params[:id])
  end

  def update
    @category = Category.find(params[:category_id])
    @photo = @category.photos.find(params[:id])

    respond_to do |format|
      if @photo.update_attributes(params[:photo])
        format.html { redirect_to @category, notice: "<i class=icon-ok /> #{@category.name} was successfully updated."}
        format.js
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @category.errors, status: :unprocessable_entity }
      end
    end
  end
  def new
    @category = Category.find(params[:category_id])
    @photo = @category.photos.new
  end
  def destroy
    @category = Category.find(params[:category_id])
    @photos = @category.photos
    @photo = @photos.find(params[:id])
    @photo.destroy
    redirect_to @category, :notice => "Photo deleted."
  end
end

私の写真モデルには次のものがあります。

class Photo
  include Mongoid::Document
  embedded_in :category, :inverse_of => :photos

  field :image
  attr_accessible :image

  # Set uploader
  mount_uploader :image, ImageUploader
end

カテゴリモデルの場合:

class Category
  # Includes to set up the model
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Ancestry
  include Mongoid::Versioning
  include Mongoid::Paranoia
  include Mongoid::Slug
  include Mongoid::History::Trackable

  # tell it that it can go nest itself
  has_ancestry
  embeds_many :photos

  # Accept nested attributes
  accepts_nested_attributes_for :photos, :autosave => true
  # tell history how it can track things
  track_history   :on => [:name, :description],   # track these fields
                  #:modifier_field => :modifier, # adds "referenced_in :modifier" to track who made the change, default is :modifier
                  :version_field => :version,   # adds "field :version, :type => Integer" to track current version, default is :version
                  :track_create   =>  false,    # track document creation, default is false
                  :track_update   =>  true,     # track document updates, default is true
                  :track_destroy  =>  false    # track document destruction, default is false
  # Keep at most 5 versions of a record
  max_versions 5

  # Add the models fields here
  field :name, type: String
  field :ancestry, type: String
  field :description, type: String

  # Set which field the url slug should use
  slug :name

  # Make sure these attributes can be accessed
  attr_accessible :ancestry, :name, :parent_id, :description

  # Make name fields capitalized on save
  def name=(t)
    write_attribute(:name, t.to_s.split(' ').map {|w| w.capitalize}.join(' '))
  end

  # Create some scopes
  scope :except, lambda{ |category| where("id <> ?", category.id)}
end

ノート:

たくさんのコードを貼り付けたところです。具体的に答えるためにコードを解析する時間があまりなかったからです。うまくいけば、私のコードのいくつかを書いた方法があなたを助けることができます。

私が使用していることを覚えておいてください:

  • Mongoid
  • Rails 3

乾杯、

-ブランドン

于 2013-02-05T05:13:29.667 に答える