我在ruby-on-rails中用自定義表單設法做了幾乎所有的快樂事情,但最後一步已經失蹤,無法找到答案因爲太多的常用詞彙網。RoR:如何處理自定義嵌套表單的提交
我相信我的問題的答案對於一段時間內完成RoR的人來說是微不足道的,但要注意的是,問題的表述會有些複雜。
讓我們來看看一個等價的問題!
模式:
publishers (id, name, address)
books (id, title, publisher_id, publishing_year, unit_price, qty)
sell_log (id, user_id, timestamp, book_id, qty, unit_price, comment)
自定義操作:
名稱:賣(上下文:一本書)
輸入:
qty
,comment
,(隱式輸入:book.id
,timestamp
;衍生的輸入:user_id
,,book.qty
)結果:
sell_log附加
books.qty降低
可能的錯誤:
數量是非正數或非整數。
在用戶輸入的數量超出了可用的數量(book.qty)
更大(FYI:這不是一個有關數據庫設計的問題。)
所以我們有一個自定義的表單(隱藏的book-id; qty,comment),我們想要將其作爲一個類似於「編輯」書籍的行爲來實現(update
)。什麼是(幾乎所有):
- books_controller.rb:添加custom_qty_display
列。
- books_helper.rb:
def custom_qty_display_column(record)
record.qty.to_label + " ["
link_to("Sell..." \
, { :controller => "books", :action => "sell_form", :id => record.id, :page => false } \
, { :position => "replace", :inline => true, :class => "action" } \
) \
+ "]"
end
- 視圖/書籍/ sell_form。ERB(唯一的關鍵細節)
<%
form_remote_tag(\
:url => { :controller => :books, :action => :sell, :id => params[:id] } \
) do
%>
...
<%= submit_tag 'Submit' %>
<%= link_to as_(:cancel), main_path_to_return, :class => 'cancel' %>
<% end %>
<div id="as_books-messages" class="messages-container" />
- books_controller.rb:
def sell
errors = [] # We will collect error messages here
# Checking parameters ...
# Checking of available qty ...
# If "errors" is still empty here, perform the action
# Produce the output according to the above:
if request.xhr?
if errors.empty?
# Q1: rendering of javascript which replaces the form with the modified row in the table.
else
# Q2: rendering of javascript which provides the "errors" for the user
end
else
if errors.empty?
index
else
# Q3: Redisplay the form and errors
end
end
end
最新研究進展
當我點擊 「賣出...」 鏈接一書列表條目該條目消失,自定義窗體出現,而不是它。在表單上的「取消」鏈接(和[X]按鈕)完美地工作; SUBMIT按鈕有效(當輸入正確時,操作成功完成)。
什麼是不存在的形式仍然存在。理論上,我應該在標有Q1
,Q2
和Q3
的地方返回適當的javascript。我不想逆向工程並用手寫javascript,因爲在框架升級時我會被迫重做這一步。我想以簡單和可維護性最好的方式製作必要的javascript。因爲我現在相信我的概念並不差。
版本信息
- 的JRuby 1.5.0
- 寶石
- 軌2.3.4
- 的ActiveRecord 2.3.4
- 的ActiveSupport 2.3.4
(告訴我,如果別人需要什麼)
部分結果
# ...
if errors.empty?
render :action => 'on_update.js'
else
# ...
end
# ...
ARGH ...錯過了問題中的觀點。無論如何,因爲這是與部隊的一週戰鬥。這對宇宙是有價值的(我希望)。請參閱編輯日誌 – Notinlist 2010-09-02 09:09:25