如何让这段代码变得更好? (sinatra + 数据映射器)
我对此很陌生,我正在使用 datamapper 和 sinatra 来构建一个基本的应用程序。我有一个设置页面,其中包含一些用于几种不同设置的文本输入。
查看此页面时,应该从数据库中提取信息并填充输入框(如果有)。
对于我的设置类,我有 :name 和 :value
截至目前,我的代码正在运行,如果名称尚不存在,则允许创建设置,否则会更新它。
Setting.first_or_create(:name => "seed").update(:name => "seed", :value => params[:seed])
3个问题:
如果输入为空(显然在第一次之后),它会用“”覆盖它
如何缩短这段代码?在“真正的”Ruby 程序中,我应该定义一个方法,这样就没有那么多冗余代码吗?我有 5 个设置,所以我觉得这行代码出现 5 次,只有几处不同,这有点糟糕。困难在于我将被迫将我所有的输入命名为我正在使用的确切哈希值。我不确定这是否是不好的做法,或者我是否应该明确地执行 5 次
为了“获取”数据来显示它,我有这个:
@seed = Setting.get(:name => "seed")
这显然不起作用...我需要的是获取 params[:value] WHERE :name => “种子”和使用 <%= @seed(???) %>将其打印出来。我不知道如何做到这一点
I'm new to this, and I'm using datamapper and sinatra to build a basic app. I have a settings page with a few text inputs for several different settings.
This page, when viewed, should pull the information from the database and populate the input boxes if they're there.
For my Setting class I have :name and :value
As of right now, I have the code working which allows a setting to be created if the name doesnt already exist, and it updates it otherwise.
Setting.first_or_create(:name => "seed").update(:name => "seed", :value => params[:seed])
3 problems:
if the input is blank (after the first time obviously), it overwrites it with ""
How can I shorten this code down? In a 'real' ruby program, should i define a method so theres not so much redundant code? I have 5 settings so i feel having that line of code 5 times with only a few things different is kind of poor. The difficulty is that I would be forced to name="" all my inputs the exact hash that i'm using. Im not sure if thats poor practice or not, or whether I should just do it all explicitly 5 times
In order to 'get' the data to display it i have this:
@seed = Setting.get(:name => "seed")
That obviously doesn't work... what I need is to get params[:value] WHERE :name => "seed" and the use <%= @seed(???) %> to print it out. im not sure how to do this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)