【问题标题】:Use coffeescript or javascript in rails form to grab model attribute使用 rails 形式的 coffeescript 或 javascript 来获取模型属性
【发布时间】:2017-04-16 09:07:21
【问题描述】:

我正在开发一个 Rails 应用程序,需要一些关于我不太擅长的咖啡脚本的帮助。

我有一个表单,其中包含一个名为 location_id 的字段,使用 Rails 中的集合。

<%= f.grouped_collection_select :location_id, Region.order(:area), :active_locations, :area, :id, :location_name_with_address, {include_blank: true}, class: 'select' %>

Location 模型上有一个名为modifier 的列,其中包含一个值。在我的表单中,我需要能够获取 modifier 值以在客户端评估它以显示/隐藏 div。

我开始编写我的咖啡脚本,并且能够像这样获得Locationid

$('#call_location_id').val()

但我不知道该怎么做是,我如何获取该位置的id,并评估模型属性modifier?我不确定如何在客户端获取它。

我用谷歌搜索并阅读了很多咖啡脚本 sn-ps,但似乎找不到正确的方向。

我只需要在正确的道路上有所突破,这样我就可以自己解决剩下的问题。

【问题讨论】:

  • 你能给我们展示一个呈现 HTML 的例子吗?
  • @max 你想要屏幕截图还是从 Chrome 检查器吐出的实际 html?
  • 嗯,我考虑了一下。您可以向 /locations/:id 发送 JSON ajax 请求,这将呈现位置的详细信息。
  • 或者您创建自己的 grouped_collection_select 版本,其中包括 location.modifier 作为选项元素上的数据属性。您可以通过侦听更改事件并在事件处理程序中使用$(this).children("option:selected"); 来获取选择选项。
  • ajax 方法很可能是最简单的,但可能会有一点延迟。

标签: javascript jquery ruby-on-rails ruby-on-rails-3 coffeescript


【解决方案1】:

我能够通过 select 语句解决这个问题,并在传递数据属性的同时映射位置,让我通过 coffeescript 抓取。

<%= f.select :location_id, grouped_options_for_select(Region.order(:area).map{ |group| [group.area, group.locations.order('location_name asc').map{ |o| [o.location_name, o.id, {'data-modifier'=>o.location_modifier, 'data-name'=> o.location_name}] } ] }, f.object.transfer_from_id), {:include_blank => true}, {:class => 'select'} %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    相关资源
    最近更新 更多