【发布时间】:2013-04-10 20:46:19
【问题描述】:
总结:
如何自定义respond_to 为 ActiveModel 对象生成的路径?
更新:我正在寻找一个钩子、方法覆盖或配置更改来完成此操作,而不是解决方法。 (解决方法很简单,但并不优雅。)
背景与示例:
这里有一个例子来说明。我有一个模型,Contract,它有很多字段:
class Contract < ActiveRecord::Base
# cumbersome, too much for a UI form
end
为了让 UI 代码更易于使用,我有一个更简单的类,SimpleContract:
class SimpleContract
include ActiveModel::Model
# ...
def contract_attributes
# convert SimpleContract attributes to Contract attributes
end
def save
Contract.new(contract_attributes).save
end
end
这很好用,但我的控制器有问题...
class ContractsController < ApplicationController
# ...
def create
@contract = SimpleContract.new(contract_params)
flash[:notice] = "Created Contract." if @contract.save
respond_with(@contract)
end
# ...
end
问题是respond_with 指向simple_contract_url,但是我希望它指向contract_url。最好的方法是什么? (请注意,我使用的是 ActiveModel。)
(注意:我使用的是 Rails 4 Beta,但这不是我的问题的核心。我认为 Rails 3 的一个好的答案也可以。)
边栏:如果您觉得这种将模型包装在轻量级 ActiveModel 类中的方法不明智,请在 cmets 中告诉我。就个人而言,我喜欢它,因为它使我的原始模型保持简单。 “包装器”模型处理一些 UI 细节,这些细节被有意简化并提供合理的默认值。
【问题讨论】:
标签: ruby-on-rails routing activemodel ruby-on-rails-4