Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在rails中向视图添加条件输入的更好方法是什么?_Ruby On Rails - Fatal编程技术网

Ruby on rails 在rails中向视图添加条件输入的更好方法是什么?

Ruby on rails 在rails中向视图添加条件输入的更好方法是什么?,ruby-on-rails,Ruby On Rails,我有一个我正在逐步建立的页面预览视图。当前预览视图不起作用,它只有一个带有默认文本和样式的默认页面。我的任务是在用户通过表单提交页面元素时显示预览。这是默认视图的外观: <h1> Worlds coolest Product </h1> <h3> Buy me and make your life 10x more worthwhile! :) </h3> 世界上最酷的产品 买我,让你的生活更有价值!:) 这个默认文本是由一个部分渲染出

我有一个我正在逐步建立的页面预览视图。当前预览视图不起作用,它只有一个带有默认文本和样式的默认页面。我的任务是在用户通过表单提交页面元素时显示预览。这是默认视图的外观:

<h1>
  Worlds coolest Product
</h1>

<h3>
Buy me and make your life 10x more worthwhile! :)
</h3>

世界上最酷的产品
买我,让你的生活更有价值!:)
这个默认文本是由一个部分渲染出来的,如下所示:

<%= render 'manage/deal_steps/deal/main_header' %>

我的问题是,如果有,我需要用用户提交的文本替换默认文本,但我还需要保留默认文本,以防用户不提交任何内容。这样,如果没有错误,我就不会得到任何错误 输入。保持简单,是否有任何方法可以实现这一效果,而不将视图与以下条件逻辑混为一谈:

<h1>
  <%if retrieve_content('header')!= nil %>
  <%= retrieve_content('header')%>
  <%else%>
  Worlds coolest Product
  <% end%>
</h1>

<h3>
<%if retrieve_content('header_two')!= nil %>
  <%= retrieve_content('header_two')%>
<%else%>
Buy me and make your life 10x more worthwhile! :)
<%end%>
</h3>

世界上最酷的产品
买我,让你的生活更有价值!:)

修改“检索内容”方法以接受第二个可选属性defualt。它看起来像:

def retrieve_content(key, default = nil)
  <Your old logic> || default
end
def检索内容(键,默认值=nil)
||违约
结束
然后您可以使用它:

<h1>
  <%= retrieve_content('header', 'Worlds coolest Product') %>
</h1>


如果默认文本更复杂(包括html和其他内容),请接受可选块并使用捕获帮助程序。

修改“检索内容”方法以接受第二个可选属性defualt。它看起来像:

def retrieve_content(key, default = nil)
  <Your old logic> || default
end
def检索内容(键,默认值=nil)
||违约
结束
然后您可以使用它:

<h1>
  <%= retrieve_content('header', 'Worlds coolest Product') %>
</h1>


如果默认文本要复杂得多(包括html和其他内容),请接受可选块并使用捕获帮助程序。

这将为您提供与当前代码相同的结果:

<h1>
  <%= retrieve_content('header') || 'Worlds coolest Product' %>
</h1>

<h3>
  <%= retrieve_content('header_two') || 'Buy me and make your life 10x more worthwhile! :)' %>
</h3>

这将为您提供与当前代码相同的结果:

<h1>
  <%= retrieve_content('header') || 'Worlds coolest Product' %>
</h1>

<h3>
  <%= retrieve_content('header_two') || 'Buy me and make your life 10x more worthwhile! :)' %>
</h3>


查看Rails中的
演示者
。嘿,谢谢你的提示。我调查了一下。这似乎是一种从视图中提取逻辑并生成可重用视图方法的好方法,我可以将这些方法放入视图中。:)仍然没有办法离开条件方法,但它确实使视图更清晰。所以我会接受这个答案。感谢您查看Rails中的
演示者
。嘿,我感谢您提供的提示。我调查了一下。这似乎是一种从视图中提取逻辑并生成可重用视图方法的好方法,我可以将这些方法放入视图中。:)仍然没有办法离开条件方法,但它确实使视图更清晰。所以我会接受这个答案。谢谢你的机智,这正是我想要解决的问题。我打算使用presenter,但这无疑会使presenter类变得杂乱无章。谢谢你,非常机智,这正是我想要解决的问题。我打算使用presenter,但这无疑会使presenter类变得杂乱无章。非常感谢。