从多个地方渲染javascript:Rails方式

asc*_*man 8 ruby-on-rails coffeescript turbolinks

我有一个通过javascript呈现的模态表单.该模型被称为.

# controllers/books_controller.rb

def new
  @book = Book.new
end

def create
  @book = Book.find(params[:id])
  @book.save
end
Run Code Online (Sandbox Code Playgroud)

我没有使用新的和编辑html,而是使用coffeescript:

# views/new.js.coffee

CustomModal.open "<%= j render('books/modal_form', book: @book) %>"
Run Code Online (Sandbox Code Playgroud)

-

# views/create.js.coffee

<% if @book.valid? %>
CustomModal.hide()
# Other callback scripts for showing alert, etc
<% else %>
# Script for showing errors in the modal
<% end %>
Run Code Online (Sandbox Code Playgroud)

以及触发模态的链接:

= link_to "Create Book", new_book_path, remote: true
Run Code Online (Sandbox Code Playgroud)

现在,我面临的问题是这个链接只是在书的列表页面上使用.因此,在创建图书时,js回调会触发警报并使用更改更新列表.

现在我必须在另一个页面中添加此按钮,其中没有列表,所以我需要一个不同的回调(无论哪个回调都没关系).

所以,我必须添加到create.js.coffee之类的东西:

# views/create.js.coffee

<% if @book.valid? %>
CustomModal.hide()
# if the list exists
#   show alert
#   update lists
# else
#   do different things
# end
<% else %>
# Script for showing errors in the modal
<% end %>
Run Code Online (Sandbox Code Playgroud)

这看起来很脏,但并不是那么糟糕.问题是我现在有超过3个条件,因为沿着webapp多次使用"Create Book"按钮.

那么,关于这个设计模式的任何想法?

sp8*_*p89 0

您可能需要考虑将成功/错误逻辑保留在控制器中,而是根据成功/失败使用单独的视图。所以你就有了 acreate_success.js.coffee和 a create_error.js.coffee。每个人只处理自己的情况,不关心对方。注意:这是伪代码。

# controller
def create
  @book = Book.find(params[:id])

  if @book.save # save will run validations
     render :create_success
  else
     render :create_error
  end
end

# Views
#
# create_success.js.coffee
CustomModal.hide()
# other stuff you do if successful


# create_error.js.coffee
# re-render form with errors
# assuming the modal is already open, you might want to just replace the form, rather than re-open the modal. 
$(".myFormSelector").html("<%= j render('books/modal_form', book: @book)%>")
Run Code Online (Sandbox Code Playgroud)