草庐IT

java - 在 Grails 中发布嵌套资源的问题

coder 2024-04-05 原文

我在理解 Grails Restful Controller 的工作原理时遇到问题。我正在尝试向嵌套资源发出发布请求(见下文)。我不确定我是否理解我需要更改什么才能使这项工作正常进行,因为 GET 请求似乎建立了 Bid 与其父资源项目的关联,但是当我尝试 POST 时,我被警告该项目不能为空。

感谢任何帮助!

Item.groovy

class Item {
    static hasMany = [bids:Bid]
}

Bid.groovy

class Bid {
    Integer ownerId
    Double amount

    static belongsTo = [item:Item]

    static constraints = {
        ownerId nullable: false
        amount nullable: false
    }
}

BidController.groovy

class BidController extends RestfulController<Bid> {
    static responseFormats = ['json', 'xml']
    BidController() {
        super(Bid)
    }
    @Override
    def getObjectToBind() {
        request.parameterMap.put('itemId', params.itemId)
        return request
    }
}

ItemController.groovy

class ItemController extends RestfulController<Item> {
    static responseFormats = ['json', 'xml']
    ItemController() {
        super(Item)
    }
}

UrlMappings.groovy

class UrlMappings {

    static mappings = {
        "/items"(resources:"item") {
            "/bids"(resources: "bid")
        }
    }
}

URL 映射

Controller: item
 |   GET    | /items                                                    | Action: index            
 |   GET    | /items/create                                             | Action: create           
 |   POST   | /items                                                    | Action: save             
 |   GET    | /items/${id}                                              | Action: show             
 |   GET    | /items/${id}/edit                                         | Action: edit             
 |   PUT    | /items/${id}                                              | Action: update           
 |  PATCH   | /items/${id}                                              | Action: patch            
 |  DELETE  | /items/${id}                                              | Action: delete    
Controller: bid
 |   GET    | /items/${itemId}/bids                                     | Action: index            
 |   GET    | /items/${itemId}/bids/create                              | Action: create           
 |   POST   | /items/${itemId}/bids                                     | Action: save             
 |   GET    | /items/${itemId}/bids/${id}                               | Action: show             
 |   GET    | /items/${itemId}/bids/${id}/edit                          | Action: edit             
 |   PUT    | /items/${itemId}/bids/${id}                               | Action: update           
 |  PATCH   | /items/${itemId}/bids/${id}                               | Action: patch            
 |  DELETE  | /items/${itemId}/bids/${id}                               | Action: delete                    

发布请求

POST /AuctionService/items/1/bids HTTP/1.1
Content-Type: application/json
Host: localhost:8080
Connection: close
Content-Length: 34

{
    "ownerId": 1,
    "amount": 3.00
}

回应

HTTP/1.1 422 Unprocessable Entity
Server: Apache-Coyote/1.1
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 25 Jul 2014 17:44:03 GMT
Connection: close

{"errors":[{"object":"auctionservice.Bid","field":"item","rejected-value":null,"message":"Property [item] of class [class auctionservice.Bid] cannot be null"}]}

最佳答案

我认为您可以通过覆盖 createResource() 方法来完成您想要的。

@Override
protected Bid createResource() {

    Bid bid=super.createResource();
    bid.item=Item.get(params.itemId)
    return bid;
}

当使用嵌套 URL 时,其他默认 Controller 操作可能无法按预期工作。 如果您想确保只返回属于 URL 中的项目的出价,您可能还想覆盖 queryForResource 和索引

@Override
protected Stay queryForResource(Serializable id) {
    def itemId=params.itemId

    Bid.where {
        id==id &&  item.id == itemId
    }.find()

}

def index(Integer max) {
    params.max = Math.min(max ?: 10, 100)
    def itemId=params.itemId
    respond Bid.where {
        item.id==itemId
    }.list(params)
}

关于java - 在 Grails 中发布嵌套资源的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24961909/

有关java - 在 Grails 中发布嵌套资源的问题的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  3. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  4. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  5. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  6. ruby - Fast-stemmer 安装问题 - 2

    由于fast-stemmer的问题,我很难安装我想要的任何ruby​​gem。我把我得到的错误放在下面。Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingfast-stemmer:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcreatingMakefilemake"DESTDIR="cleanmake"DESTDIR=

  7. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  8. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  9. Ruby——嵌套类和子类是一回事吗? - 2

    下面例子中的Nested和Child有什么区别?是否只是同一事物的不同语法?classParentclassNested...endendclassChild 最佳答案 不,它们是不同的。嵌套:Computer之外的“Processor”类只能作为Computer::Processor访问。嵌套为内部类(namespace)提供上下文。对于ruby​​解释器Computer和Computer::Processor只是两个独立的类。classComputerclassProcessor#Tocreateanobjectforthisc

  10. ruby - 模块嵌套代码风格偏好 - 2

    我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的

随机推荐