简体   繁体   English

控制器助手在轨道上的红宝石

[英]Controller helpers in ruby on rails

I am new to rails and am wondering if this is the best way to go about what I want to do. 我是Rails的新手,我想知道这是否是实现我想要做的最好的方法。

I have a controller that creates entities. 我有一个创建实体的控制器。

Depending what gets submitted I want to either create a new entity from scratch, or copy an existing one. 根据提交的内容,我想从头开始创建一个新实体,或者复制一个现有实体。

So far I have 到目前为止,我有

def create
  if(params[:copy])
    return copy_existing_entity params
  else
    return create_new_entity params
  end
end

So far this feels icky - should this be done differently? 到目前为止,这感觉很糟糕-是否应该以其他方式进行?

Coming from java spring, I would just define separate handlers on the controller like so: 来自java spring,我将像这样在控制器上定义单独的处理程序:

@RequestMapping(method = RequestMethod.POST, params="submit=Action 1")
public ModelAndView action1(@RequestParam("selectedItemKey") String key) {
    ModelAndView mav = new ModelAndView("action1");
    //Business logic
    return mav;
}

@RequestMapping(method = RequestMethod.POST, params="submit=Action 2")
public ModelAndView action2(@RequestParam("selectedItemKey") String key) {
    ModelAndView mav = new ModelAndView("action2");
    //Business logic
    return mav;
}

Does rails provide something like this or am I thinking about this the wrong way? Rails是否提供类似的东西,或者我是否在以错误的方式考虑?

Thanks for any suggestions 感谢您的任何建议

This does seem kind of bad. 这似乎有点不好。 First of all, why are you copying entities in the first place? 首先,为什么要首先复制实体? What's your use case? 您的用例是什么?

Second, you're probably putting the logic in the wrong place. 其次,您可能将逻辑放在错误的位置。 You should probably either (1) have separate create and copy controller actions, or (2) pass params on to the model class and let it figure out whether it's creating or copying. 您可能应该(1)具有单独的createcopy控制器操作,或者(2)将params传递给模型类,并让其确定是创建还是复制。

You could easily split it apart in two controller actions, but actually I do believe that in both cases you are creating a new Entity. 您可以轻松地将其拆分为两个控制器操作,但是实际上,我确实相信在两种情况下都可以创建新的实体。 So a POST :create is the good REST way. 因此POST :create是一种很好的REST方法。 And if you have to create a new item filled up with the given attributes, or create a new item as a copy from another does not really matter imho. 而且,如果您必须创建一个充满给定属性的新项目,或者创建一个新项目作为另一个项目的副本,恕我直言并不重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM