Re: [問題] RoR下如何使用select撈資料呢?
自已打的問題自已解決
我最後是用Ruby on rails的ProtoTypeHelper做到的
方法如下:
在PC的controller下
新增一個brand anction, 傳入品牌id, 回傳屬該品牌的型號
def brand
# Is this an XmlHttpRequest request?
if (request.xhr?)
@pcs = PC.all(:conditions => ["brand_id = ?", params[:q]])
result = ""
for pc in @pcs
result << "<option value=#{pc.id}>#{pc.name}</option>"
end
render :text => result
else
# No? Then render an action.
render :text => ""
end
end
然後在Order的new, edit的view下
新增
<%
pcs = PC.all(:group => 'brand_id', :order => "name asc")
result =""
for pc in pcs
if @order.pc.brand_id == pc.brand_id
result << "<option value=#{pc.brand_id} selected='selected'>#{pc.brand.name}</option>"
else
result << "<option value=#{pc.brand_id}>#{pc.brand.name}</option>"
end
end
%>
<%= select_tag "brand", result %>
<%= select("sheet", "brand_id", PC.all.sort_by {|a| a.name}.collect {|p| [ p.brand.name + '/' + p.name, p.id ] }, { :include_blank => true }) %>
<%= observe_field :brand, :url => '/pcs/brand',
:frequency => 1,
:update => :order_pc_id,
:with => 'q'
%>
這樣就可以用下拉式選單選廠牌, 然後只顯示該廠牌相關的電腦.
這邊要注意的地方只有一個, observe_field要放在被觀察的欄位後面, 不然怎麼試都會沒反應
希望我的經驗可以幫助到大家
※ 引述《dickstar (To you)》之銘言:
: 環境:
: Ruby 1.8.7 & Rails 2.2.2
: 狀況:
: 我在想用form_helper做到一件事, 動態撈資料
: 例如:
: class Brand < ActiveRecord::Base
: has_many :PCs
: end
: class PC < ActiveRecord::Base
: belongs_to :brand
: has_many :orders
: end
: class Order < ActiveRecord::Base
: belongs_to :PC
: end
: 我在Order的Add View裡可以使用
: <%= collection_select(:sheet, :PC_id, PC.all, :id, :name, {:include_blank => true}) %>
: 可是資料多的時侯就要翻好幾頁才找的到資料
: 請問要如何做先選擇品牌, 選完之後再選擇相關的PC呢?(感覺像是兩階段的select)
: 感謝大大們賜教?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.127.157.91
※ 編輯: dickstar 來自: 59.127.157.91 (03/11 13:17)
※ 編輯: dickstar 來自: 59.127.157.91 (03/11 13:19)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
Ruby 近期熱門文章
PTT數位生活區 即時熱門文章