正确地压倒适当的曝光
Rails 3.0.7 + Decent Exposure Gem
我正在为具有一个关联属性的模型创建一个表单:
class Foo
has_many :bars
def self.build_next(attributes={})
if item = last.try(:clone)
# ... overrides
else
item = self.new
end
item.attributes = attributes
return entry
end
end
允许用户从选择框中选择关联项之一。所以我的基本控制器如下所示:
class FooController < ApplicationController
expose(:foos)
expose(:foo)
expose(:bar)
def new
#...
end
def create
if foo.save
redirect_to foo
else
render :action => 'new'
end
end
end
这很好用,但需要调整功能以克隆前一个项目而不是创建新项目。所以我补充道:
default_exposure do |name|
collection = name.to_s.pluralize
if respond_to?(collection) && collection != name.to_s && send(collection).respond_to?(:scoped)
proxy = send(collection)
else
proxy = name.to_s.classify.constantize
end
if id = params["#{name}_id"] || params[:id]
proxy.find(id).tap do |r|
r.attributes = params[name] unless request.get?
end
else
# NEW CODE
if name == :foo && params[:action] == :new.to_s
# override
Foo.build_next
else
proxy.new(params[name])
end
end
end
这完全有效,但它几乎破坏了我的乐趣。它超级巨大而且非常草率。一定有更好的方法吧?
Rails 3.0.7 + Decent Exposure Gem
I'm creating a form for a model with one associated attribute:
class Foo
has_many :bars
def self.build_next(attributes={})
if item = last.try(:clone)
# ... overrides
else
item = self.new
end
item.attributes = attributes
return entry
end
end
The user is allowed to select from a select box one of the associated items. So my basic controller looks like this:
class FooController < ApplicationController
expose(:foos)
expose(:foo)
expose(:bar)
def new
#...
end
def create
if foo.save
redirect_to foo
else
render :action => 'new'
end
end
end
This works great, but the functionality needs to be adjusted to clone the previous item instead of creating a new one. So I've added:
default_exposure do |name|
collection = name.to_s.pluralize
if respond_to?(collection) && collection != name.to_s && send(collection).respond_to?(:scoped)
proxy = send(collection)
else
proxy = name.to_s.classify.constantize
end
if id = params["#{name}_id"] || params[:id]
proxy.find(id).tap do |r|
r.attributes = params[name] unless request.get?
end
else
# NEW CODE
if name == :foo && params[:action] == :new.to_s
# override
Foo.build_next
else
proxy.new(params[name])
end
end
end
This totally works, however it pretty much ruins my fun. It's super huge and is incredibly sloppy. There must be a better way right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不在模型的 before 回调中而不是在控制器中执行此操作?
例如
Why not do this in a before callback on the model instead of in the controller?
e.g.