开发者

Ruby on Rails - Ajax to retrieve associated data of selection made

开发者 https://www.devze.com 2023-01-31 07:06 出处:网络
Am a RoR newbiw and your help would be much appreciated. I have 3 models - submission, supplier and lnksupplier

Am a RoR newbiw and your help would be much appreciated.

I have 3 models - submission, supplier and lnksupplier

class Submission < ActiveRecord::Base
has_many :lnksuppliers, :dependent => :destroy
has_many :suppliers, :through => :lnksupplier
accepts_nested_attributes_for :lnksuppliers
end

class Lnksupplier < ActiveRecord::Base
belongs_to :submission,  
belongs_to :supplier
end

class Supplier < ActiveRecord::Base
has_many :lnksuppliers, :dependent => :destroy
has_many :submissions, :through => :lnksupplier
end

the lnk_supplier table has 3 fields - its primary key, supplier_id, submission_id. To associate a supplier to a submission, user selects from a drop down list containing all the suppliers retrieved from the supplier table and the id is stored in the lnk_supplier table. See code below:

    <%= f.select(:supplier_id, options_for_select(Supplier.find(:all).collect {|p| [ p.SUP_COMPANY, p.ID ] })) %> 



  <%= observe_field("submission_lnksuppliers_attributes_0_LPL_SUP_FK",
      :update => "span1",
      :url => { :action => :find_supplier_detai开发者_如何学Cls },
      :with => "'id='+value") %>


Check out observe_field; it lets you pass the selected value from your drop-down to a Rails controller via Ajax. Then, in your controller, you use the selected ID to retrieve the model and render the result back to the page.

Edited to add: OK, the observe_field code you posted is a good start; the rest is: 1) in your controller, get the id from params and use it to retrieve the data associated with that supplier, and 2) render an rjs file that specifies which element on the page to add that data to, and which partial to use to render that data as HTML.

0

精彩评论

暂无评论...
验证码 换一张
取 消