2013-03-01 155 views
1

我有三個表與指定的字段/列在括號:國家selction貨幣顯示

Country (name,currency_id) 
Currency (name) 
User (name ,country_id,currency_id) 

我的要求是在創建在全國用戶選擇,默認貨幣需要首先是顯示器和剩餘的貨幣顯示在下一個選擇行中。 EX:如果我們選擇美國在國家下拉幣下拉美元需要先顯示餘下的貨幣

我的想法是用戶屬於任何國家默認貨幣是他的國家貨幣,他有選擇選擇其他貨幣也。

請幫助我。

+0

你想默認貨幣來選擇,或者它應該永遠是第一個選項? – 2013-03-01 17:21:50

+0

它應該永遠是第一個選項感謝 – user1629670 2013-03-01 17:52:34

+0

請幫我 – user1629670 2013-03-01 17:55:04

回答

0

你知道,用戶所屬的國家,用戶屬於貨幣。您還需要country_to default_currency。

class Country 
    belongs_to :default_currency, :class_name => "Currency" 
-1

User不需要currency_id,因爲這可以從它屬於Country導出。您可以將方法添加到User以按正確的順序取回貨幣。

class User < ActiveRecord::Base 
    ... 
    def ordered_currencies 
    # Set up an array of currencies, with the default one first. 
    default_currency = self.country.currency 
    currencies = [default_currency.name] 

    # Add in all other currencies except the default one. 
    Currency.where("id != ?", defauly_currency.id).each do |currency| 
     currencies << currency.name 
    end 

    return currencies 
    end 
    ... 
end 

在這種情況下,我提出的方法返回回到貨幣的名字,但如果你想要回Currency對象本身,你可以很容易地改變它。

+0

'用戶屬於任何國家的默認貨幣爲他國貨幣與他有選項可以選擇其他貨幣also' – 2013-03-01 17:20:38

+0

我認爲有一些在那裏缺少標點符號/單詞。 「用戶屬於任何國家,用戶的默認貨幣是他的國家的貨幣。」 – MrDanA 2013-03-01 17:32:15

+0

錯誤時被顯示 – user1629670 2013-03-01 17:45:58

0

我假設,你必須在用戶形成兩個選擇框爲:

<%= f.select :country_id, options_for_select(@countries.map{ |c| [c.name, c.id, {'data-currency'=>c.currency.id}] }), {}, :id => 'user_country' %> 
<%= f.collection_select :currency_id, @currencies, :id, :name, {}, :id => 'user_currency'%> 

在全國選擇將有一個額外的屬性data-currency選項,可以在jQuery的可以用來找到正確的貨幣期權。該@countries@currencies是:

@countries = Country.includes(:currency).all 
@currencies = Currency.all 

現在jQuery中,

$(document).ready(function(){ 
    $('#user_country').change(function(){ 
    var currency_id = $(this).find("option:selected").data('currency'); //collects the value of `data-currency` attribute of selected country. 

    var currency_option = $('#user_currency').find("option[value='" + currency_id + "']"); //finds the option tag with the currency_id as value. 
    $('#user_currency').prepend(currency_option); //prepends the currency_option to the currency select 

    //the currency will be the first option now but it will not be selected by default 
    //to make it selected replace the last line with 
    //$('#user_currency').prepend(currency_option.attr('selected', 'selected')); 
    }); 
});