简体   繁体   中英

Indicate to Rails controller which view called action

I have two views which commit a similar controller create action, allowing the user to "Track" a product. Upon clicking the "Track" button, each view submits an AJAX request via remote: true attribute, and the javascript response should re-render the corresponding partial that called it. How can I indicate to my create.js.haml script which view called the action and then respond accordingly?

Code:

Partial #1

- if current_user.present? && current_user.tracked_products.include?( @media )
    %a.btn.btn-responsive.btn-thin.btn-color.red-bg{ href: main_app.price_tracker_path( current_user.price_trackers.where( product_id: @media.id  ).first, _method: :delete ), style: 'font-size: 1.2em', data: { method: :delete, remote: true } }
        -# %i.fa.fa-eye-slash
        Stop Tracking
- elsif current_user.present?
    %a.btn.btn-responsive.btn-thin.btn-color.brand-background-color-lavender{ href: main_app.modal_new_price_trackers_path( media_id: @media.slug ), style: 'font-size: 1.2em', data: { toggle: :modal, target: '#new_price_tracker' } }
        -# %i.fa.fa-eye
        Track It
- else
    %a.btn.btn-responsive.btn-thin.btn-color.brand-background-color-lavender{ href: '#', style: 'font-size: 1.2em', data: { toggle: :modal, target: '#login_modal' } }
        -# %i.fa.fa-eye
        Track It

Partial #2

- if (tracker = current_user.price_trackers.active.where( product: product ).first).present?
    %a.btn-responsive.brand-color-white{ href: main_app.price_tracker_path( tracker, _method: :delete), data: { method: :delete, remote: true} }
        %i.fa.fa-check-circle
        Track
- else
    %a.btn-responsive.brand-color-white{ href: main_app.modal_new_price_trackers_path( media_id: product.slug), data: { toggle: :modal, target: '#new_price_tracker' } }
        Track

create.js.haml:

if (//some indicator here) {
$('#track-product-'+#{@product.id}).html("#{j render(partial: 'products/track_item_from_card', locals: {product: @product})}");
else {
$('#track-item-button').html("#{j render(partial: 'products/track_item')}"); }
}

$('#new_price_tracker').attr("aria-hidden", "true");
$('#new_price_tracker').attr("style", "display: none;");

In One view you should put like this.

== button_tag 'Save', :value => 'view1', :name => 'commit', :type => 'submit'

And in second view

== button_tag 'Save', :value => 'view2', :name => 'commit', :type => 'submit'

Then in your create action check for params[:commit] to identify if it is view1 or view 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM