ruby 多态find_blablaable
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 多态find_blablaable相关的知识,希望对你有一定的参考价值。
class Like < ActiveRecord::Base
attr_accessible :user, :likeable
validates :user, :likable, {
presence: true
}
belongs_to :likeable, :polymorphic => true
belongs_to :user
validates_uniqueness_of :user_id, :scope => [:likeable_id, :likeable_type]
end
#controller
#The Ryan Bates:
def create
@likeable = find_likeable
@user = current_user
@like = @user.likes.build(likeable: @likeable)
if @like.save
redirect_to @likeable, notice: "Liked!"
else
redirect_to @likeable, notice: "Not liked!"
end
end
private
def load_commentable
resource, id = request.path.split('/')[1, 2]
@commentable = resource.singularize.classify.constantize.find(id)
end
#The Single Resource:
private
def find_likeable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
#The Nested Resource:
def create
@likeable_parent, @likeable_child = find_likeable
@user = current_user
if @likeable_child == nil
@like = @user.likes.build(likeable: @likeable_parent)
else
@like = @user.likes.build(likeable: @likeable_child)
end
if @like.save
redirect_to @likeable_parent, notice: "Liked!"
else
redirect_to @likeable_parent, notice: "Not liked!"
end
end
private
def find_likeable
likeable = []
params.each do |name, value|
if name =~ /(.+)_id$/
likeable.push($1.classify.constantize.find(value))
end
end
return likeable[0], likeable[1] if likeable.length > 1
return likeable[0], nil if likeable.length == 1
nil
end
以上是关于ruby 多态find_blablaable的主要内容,如果未能解决你的问题,请参考以下文章
ruby 在rails中创建多态关系和表单
Ruby on Rails: :include 与子模型的多态关联
ruby Rails has_many:通过多态协会(http://goo.gl/lxmehk)
ruby 使用多态数据库模型自动创建Active Record关联:http://api.rubyonrails.org/classes/ActiveRecord/Associat
ruby 中:Rails:嵌套路由,多态关联和控制器(https://medium.com/@loickartono/rails-nested-routes-polymorphic-as
Ruby类和对象