【发布时间】:2015-07-26 00:25:10
【问题描述】:
在我的应用程序中,用户有列表和 list_items(list_items 将他们添加到相应列表的产品链接)。我有一个产品搜索模式,它返回一个产品列表,每个产品都有一个 product_id 属性。我想根据用户是否已经在他们的列表中拥有产品,有条件地显示一个按钮(添加或添加)。
问题是使用了从搜索中传入的 {raw-product_id} 变量,并带有 ActiveRecord 对象查找。如果我手动输入一个整数,它可以正常工作,但是使用的变量看起来像是一个字符串,即使附加了 to_i,在使用时也不起作用:- if current_user.list_items.where(product_id: '{raw-product_id}'.to_i).exists? 底部附近的相关代码行。
代码:
-# = form_tag main_app.products_path(), method: :post do
= form_tag main_app.list_items_path, data: { passthru: current_user.nil?, remote: true } do |f|
= hidden_field_tag :success, 'back'
= hidden_field_tag :list_id, args[:list].try(:id) || '0'
.product_picker_inner
.product_picker_body
.product_picker_details
.product_picker_details_default
= hidden_field_tag :product_id, '{raw-product_id}'
= hidden_field_tag :added_from, 'search'
%h4.text-center
{escaped-title}
.text-center.product_picker_category
%span
{escaped-category}
.product_picker_content
.row
.col-xs-12.col-md-6.product_picker_avatar6
%img.img.img-responsive.center-block{ src: '#{raw-avatar}' }
-# .rectangle-avatar.contain-image{ style: 'background-image: url("{encoded-avatar}")' }
.col-xs-12.col-md-6.product_picker_description
{escaped-description}
.col-xs-12.col-md-6
.text-center{ style: 'margin:1em 2em 0.3em 0' }
price:
%b
{raw-price_formatted}
.row{ style: 'padding: 1em 0 0 0;' }
.col-xs-12
.fancy-span{ style: 'font-size: 0.8em' }
%span Tell us about this product
= text_area_tag :comment, '', class: 'form-control'
.text-center.product_picker_controlls
- if current_user.list_items.where(product_id: '{raw-product_id}'.to_i).exists?
= button_tag 'ADDED', type: 'submit', class: 'btn btn-danger btn-lg t03e', id: 'product-{raw-product_id}'
-# %a.btn.btn-primary.btn-lg.t03e{ href: "#{products_path( list_id: args[:list].try(:id) || '0', success: 'back' )}&u={raw-id}", data: { method: :post } }
ADDED
- else
= button_tag 'ADD', type: 'submit', class: 'btn btn-primary btn-lg t03e', id: 'product-{raw-product_id}'
-# %a.btn.btn-primary.btn-lg.t03e{ href: "#{products_path( list_id: args[:list].try(:id) || '0', success: 'back' )}&u={raw-id}", data: { method: :post } }
ADD
.product_picker_loading_overlay
%div{ style: 'position: absolute;top: 50%;left: 0;line-height: 1.1em;right: 0;text-align: center;font-size: 40px;margin: -20px 0 0 0;' }
%i.fa.fa-circle-o-notch.fa-spin
.text-center{ style: '' }
%a{ href: '#', 'data-dismiss' => 'modal' }
CLOSE
【问题讨论】:
-
另外,在将 ActiveRecord 查找移动到模型方法后,我注意到该方法在页面呈现后立即被调用,但在搜索之前。不知何故,我只需要在进行搜索并打开部分时调用该方法。
-
我发现部分是从 json 加载变量 {raw-product_id},从 jbuilder 文件解析。我以前没有处理过这些 - 看起来我需要一种方法来在返回 XHR 请求时重新渲染部分,或者至少是按钮。
标签: ruby-on-rails activerecord syntax