简体   繁体   English

在Rails应用程序中使用AJAX无需使用表单即可更新模型字段

[英]Using AJAX in a rails app to update a model field without using a form

I have a table that looks like this: 我有一个看起来像这样的表:

在此处输入图片说明

Each row is from this partial: 每行都来自此部分:

<div class="row chord-table-row" id= <%= "chord-#{chord.id}" %>>
    <div class="small-1 columns"><%= chord.id %></div>
    <div class="small-2 columns"><%= chord.name %></div>
    <div class="small-3 columns"><%= chord.description %></div>
    <div class="small-3 columns"><%= chord.user.username %></div>
    <div class="small-3 columns"><%= link_to 'Approve', approve_path, class: 'chord-approval-button' %></div>
</div>

How can I make the 'Approve' button go to the approve action in the chords_controller , which will update the state field of the Chord, and then run the JS/Coffeescript in approve.js.coffee ? 如何使“批准”按钮转到chords_controllerapprove动作,该操作将更新和弦的state字段,然后在approve.js.coffee运行JS / approve.js.coffee

I would (ideally) like to use remote: true in the 'Approve' link, but I am not sure how to ensure that the controller knows which Chord is being approved. 我(理想情况下)想在“批准”链接中使用remote: true ,但是我不确定如何确保控制器知道哪个Chord被批准。

Right now the #approve action looks like this: 现在,#approve操作如下所示:

def approve
  chord.approve
  # this method is on the Chord model and is working
  respond_to do |format|
    format.js
  end
end

I'd like to do this in the right "rails" way, so any guidance/advice would be much appreciated! 我想以正确的“轨道”方式进行操作,因此,任何指导/建议将不胜感激! Thanks! 谢谢!

Add a member route for approval: 添加会员路线以供批准:

resources :chords do
  member do
    post 'approve'
  end
end

Then the url helper will accept chord / chord id. 然后,URL帮助器将接受和弦/和弦ID。 You can use remote: true just like you want to: 您可以使用remote: true ,就像您想要的那样:

<%= link_to 'Approve', approve_chord_path(chord), remote: true, method: :post %>

Chord id will arrive in params as params[:id] so you can do this in your controller: 和弦id将以params[:id]进入params,因此您可以在控制器中执行此操作:

@chord = Chord.find(params[:id])
@chord.approve

Your respond_to block looks good and your JavaScript will run. 您的respond_to块看起来不错,您的JavaScript将运行。

view: 视图:

<%= link_to_function 'Approve', "$.get('#{approve_path}', {chord_id: #{chord.id}})", class: 'chord-approval-button' %>

approve.js: approve.js:

$('dom#u_need_to_change').html('<%= j render partial: 'partial_you_need_to_render' %>')

that is all 就这些

of course, you need correct routes ( get , or you can better change it to post , not really matters) and approve.js has to be in right place ( views/chords folder, i guess) 当然,您需要正确的路线( get ,或者您可以更好地将其更改为post ,这并不重要),并且approve.js必须位于正确的位置(我猜是views/chords文件夹)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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