Ruby - link_to - 如何直接从数据库添加数据

Ruby - link_to - How to add data directly from DB

首先,我是 ruby 的新手,我正在尝试维护一个已经 运行 在生产中的应用程序。

到目前为止,我已经能够 "interpret" 很好地编写代码,但是有一件事我被困住了。

我有一个 haml.html 文件,我试图在其中显示来自数据库的 links。

想象一个像下面这样的数据库结构

link_name - Home
URL - /home.html
class - clear
id - homeId

我在页面上显示一个link如下

< a href="/home.html" class="clear" id="home" > Home </a>

为此,我使用 'link_to' 添加代码如下

-link_to model.link_name , model.url, {:class => model.class ...... }

现在我有一个新的要求,我们在数据库中有一个自由文本,比如 - data-help="home-help" data-redirect="home-redirect"需要进入选项。

因此 haml 中的代码需要直接显示内容而不是将其分配给变量来显示。

也就是说我能做到 attr= '"data-help="home-help" data-redirect="home-redirect"'里面的<a>,但是做不到 data-help="home-help" data-redirect="home-redirect"<a> 标签中。

如有任何帮助,我们将不胜感激!

不确定是否可以直接嵌入属性字符串。您可以尝试解码字符串以将其传递给 link_to:

- link_to model.link_name, model.url,
    {
      :class => model.class
    }.merge(Hash[
      str.scan(/([\w-]+)="([^"]*)"/)
    ])
  )

link_to 接受 key/val 对的散列 :data => { :foo => "bar" },它将构建到锚标记上的数据属性中。上面将创建一个 attr 如下 data-foo="bar"

因此,您可以在模型上编写一个方法来获取 self.data_fields(或任何名称)并将其拆分为 attr 对,然后从中创建一个散列。然后你可以通过 :data => model.custom_data_fields_hash

将哈希直接传递给 link_to 中的 :data 参数

这种有点冗长的方法将内容拆分出来,returns 一个包含以下内容的散列:{"help"=>"home-help", "redirect"=>"home-redirect"}

def custom_data_fields_hash

  # this would be replaced by  self.your_models_attr
  data_fields = 'data-help="home-help" data-redirect="home-redirect"'

  # split the full string by spaces into attr pairs
  field_pairs = data_fields.split " "

  results = {}

  field_pairs.each do |field_pair|

    # split the attr and value by the =
    data_attr, data_value = field_pair.split "="

    # remove the 'data-' substring because the link_to will add that in automatically for :data fields
    data_attr.gsub! "data-", ""

    # Strip the quotes, the helper will add those
    data_value.gsub! '"', ""

    # add the processed pair to the results
    results[data_attr] = data_value

  end

  results

end

运行 在 Rails 控制台中给出:

2.1.2 :065 > helper.link_to "Some Link", "http://foo.com/", :data => custom_data_fields_hash
 => "<a data-help=\"home-help\" data-redirect=\"home-redirect\" href=\"http://foo.com/\">Some Link</a>"

或者,您可以将其设为帮助程序,只传入 model.data_attr 而不是

link_to "Some Link", "http://foo.com/", :data => custom_data_fields_hash(model.data_fields_attr)