加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 使用多态关联的Rails方法是什么?

发布时间:2020-12-17 03:50:02 所属栏目:百科 来源:网络整理
导读:我的Rails应用程序中的模型很少,它们是: 用户 照片 专辑 评论 我需要对照片或专辑发表评论,显然总是属于用户.我打算用polymorphic associations. # models/comment.rbclass Comment ActiveRecord::Base belongs_to :user belongs_to :commentable,:polymorp
我的Rails应用程序中的模型很少,它们是:

>用户
>照片
>专辑
>评论

我需要对照片或专辑发表评论,显然总是属于用户.我打算用polymorphic associations.

# models/comment.rb

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :commentable,:polymorphic => true
end

问题是,为新评论描述#create动作的Rails方式是什么.我看到两个选项.

1.描述每个控制器中的注释创建

但这不是一个干燥的解决方案.我可以为显示和创建注释创建一个常见的局部视图,但我将不得不重复自己为每个控制器编写注释逻辑.所以它不起作用

2.创建新的CommentsController

这是我猜的正确方法,但我知道:

To make this work,you need to declare both a foreign key column and a
type column in the model that declares the polymorphic interface

像这样:

# schema.rb

  create_table "comments",force: :cascade do |t|
    t.text     "body"
    t.integer  "user_id"
    t.integer  "commentable_id"
    t.string   "commentable_type"
    t.datetime "created_at",null: false
    t.datetime "updated_at",null: false
  end

所以,当我编写非常简单的控制器时,它将接受来自远程表单的请求:

# controllers/comments_controller.rb

class CommentsController < ApplicationController
  def new
    @comment = Comment.new
  end

  def create
    @commentable = ??? # How do I get commentable id and type?
    if @comment.save(comment_params)
      respond_to do |format|
        format.js {render js: nil,status: :ok}
      end
    end
  end

  private

  def comment_params
    defaults = {:user_id => current_user.id,:commentable_id => @commentable.id,:commentable_type => @commentable.type}
    params.require(:comment).permit(:body,:user_id,:commentable_id,:commentable_type).merge(defaults)
  end
end

我如何获得commentable_id和commetable_type?我猜,commentable_type可能是一个模型名称.

另外,从其他视图制作form_for @comment的最佳方法是什么?

解决方法

你将是最好的 nesting it in the routes,然后从父类委派:

# config/routes.rb
resources :photos,:albums do
   resources :comments,only: :create #-> url.com/photos/:photo_id/comments
end

# app/controllers/comments_controller.rb
class CommentsController < ApplicationController
   def create
      @parent  = parent
      @comment = @parent.comments.new comment_params
      @comment.save
   end

   private

   def parent
      return Album.find params[:album_id] if params[:album_id]
      Photo.find params[:photo_id] if params[:photo_id]
   end

   def comment_params
      params.require(:comment).permit(:body).merge(user_id: current_user.id)
   end
end

这将自动为您填写.

为了给自己一个@comment对象,你必须使用:

#app/controllers/photos_controller.rb
class PhotosController < ApplicationController
   def show
      @photo = Photo.find params[:id] 
      @comment = @photo.comments.new
   end
end

#app/views/photos/show.html.erb
<%= form_for [@photo,@comment] do |f| %>
  ...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读