Using STI path with same controller

旧时模样 提交于 2019-12-10 11:23:15

问题


I am using STI and am wondering, do I have to have a separate controller for each model? I have a situation where I only use the create and edit actions for one model in the STI relationship, but I get an 'undefined method' error if I try to do a form for. More specifically, I have two models that inherit from List:

class RegularList < List
class OtherList < List

and I have a lists controller that handles these actions, but I only create new models with RegularList using forms. i.e. the only situation where I use a form_for to create a new List object is with RegularList. What I would like to do is something like:

class ListsController < ApplicationController

def new
  @list = RegularList.new
end

otherwise the route for creating a new list looks like regular_list/new but I would like it to just be list/new. Thoughts?

EDIT: The problem is when I use the above code, I get an 'undefined method' error. My view looks like this:

...

So it seems that there is some problem with using a RegularList object in the Lists controller and this is the main problem I am trying to address. Sorry, I realize that was not the clearest explanation.


回答1:


I know this is kind of late, but maybe this will be helpful for other people. You want to use the becomes method. Let's say you are editing @list which is an instance of RegularList. Then do

form_for @list.becomes(List)



回答2:


I am using STI and am wondering, do I have to have a separate controller for each model?

No, you don't.



来源:https://stackoverflow.com/questions/2457777/using-sti-path-with-same-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!