新手问题 怎样让所有模型 共享一个 show 页面?

boardsky · 2012年07月06日 · 最后由 help5305fff 回复于 2012年07月14日 · 3034 次阅读

假如 有三个模型 news,jobs,apps,我想让这三个模型的 show 页面都链接到 news 模型的 show 页面里,或者其他的一个特定的 show 页面里怎么做?

render :template => 'news/show'

http://guides.rubyonrails.org/layouts_and_rendering.html#using-render

2.2.3 Rendering an Action’s Template from Another Controller

What if you want to render a template from an entirely different controller from the one that contains the action code? You can also do that with render, which accepts the full path (relative to app/views) of the template to render. For example, if you’re running code in an AdminProductsController that lives in app/controllers/admin, you can render the results of an action to a template in app/views/products this way:

render 'products/show'

#3 楼 @tech_blogbin #2 楼 @fresh_fish #1 楼 @hooopo 其实我的意思是想在控制器里面 用一个变量动态的获得三个模型, 比如 我现在的代码是: '''ruby def show @frontpages_show = Backstage::News.find(params[:id]) //想定义一个变量来获得 Backstage::News,Backstage::Jobs,Backstage::Customers //然后直接改写上一句话 @frontpages_show = ‘变量’.find(params[:id]) //但是我不知道这个变量怎么弄,用什么函数来获得类似 Backstage::News 的东西。 respond_to do |format| format.html # show.html.erb format.json { render json: @frontpages_show } end end '''

类是对象,可以直接变量赋值 back_stage_class = Backstage::News #或者通过定义方法根据情况返回其它 Class @frontpages_show = back_stage_class.find(params[:id])

#5 楼 @tech_blogbin back_stage_class = Backstage::News #这样的一个 class 名字有没有一个函数来获得

class_name = params[:class_name] back_stage_class = eval(class_name)

不过这个需求好怪.....问题描述也很乱

#7 楼 @azhao 需求可以接受,就是描述让我理解偏差了

#7 楼 @azhao #8 楼 @tech_blogbin

我的需求其实很简单,就是像 cms 那样,每个详细内容页面我都共享一个 show 页面。

按照前面几楼的做法,先把 show 页面做成一个 template,然后使用 render 渲染是最好的吧。或者也可以考虑下 render 的 action 参数

#9 楼 @boardsky 可以参考 inherited_resources 这个 gem 的实现

匿名 #12 2012年07月14日

看了半天,没看懂楼主问啥。。。 action 里你就 @record = New.new

@record = Job.new

view 里你就统一用@record来接收,然后使用,@record.title @record.class就能获得对于的 Class,而且 form 表单你传实例@record,它自己能解析式哪个类对象,提交到对应的 action 。。。 至少偶们以前公司的代码都是这样约定的,页面里单个对象用@record,对象列表用@records 就是为了 view 的共用,如果这个 view 里有其他类实例,就除了主体对象用@record,其他用自己的类表示,比如@job

需要 登录 后方可回复, 如果你还没有账号请 注册新账号