2011-01-29 84 views
2

我覺得這應該是簡單的,但我有問題得到它的工作。我試過HABTM,但我不認爲這是我需要的。國家has_many渠道選擇複選框

'Country'has_many'Channels'和'Channel'belongs_to'Country'。基本上我想在渠道表格中列出帶有複選框的國家,並在country_id中保存一系列國家。

這裏的觀點:

<%= f.label :country_id, "Countries" %><br /> 
<ul style="padding: 0; margin: 0;"> 
    <% for country in Country.find(:all) %> 
    <li style="list-style: none;"> 
     <%= check_box_tag "channel[country_ids][]", :name => "channel[country_ids][]" %> 
     <%= label_tag country.id, country.name %> 
    </li> 
    <% end %> 
</ul> 

country.rb

class Country < ActiveRecord::Base 
    has_many :channel 
    has_many :satellites 
    has_many :statistics 
    has_many :testimonies 
    has_many :videos 
    attr_accessible :name, :coords 

    def hash 
    name.gsub(" ", "_").downcase 
    end 
end 

channel.rb

class Channel < ActiveRecord::Base 
    belongs_to :countries 
    attr_accessible :name, :logo, :country_id 
end 

我會做同樣的事情衛星,統計,證詞和視頻。

任何幫助表示讚賞。謝謝!

僅供參考,我用Rails 2.3.8和Rails的不這樣做3.

+0

「保存在COUNTRY_ID國家的數組」 ......嗯? – tybro0103 2011-02-04 14:57:16

回答

0

你說:

保存國家的一個數組中的 COUNTRY_ID

當你在頻道上指定country_id表示該頻道屬於一個國家/地區。這聽起來更像是你想要一個頻道擁有許多國家,但也許它是你想要的M:M關係?無論哪種方式,你不能「保存一個數組」到country_id或模型上的任何字段......至少不是你想要完成的。

此外,belongs_to :countriesbelongs_to :country

2

如果你的意思是你想商店國家的ID在頻道表一個字符串字段列表,這是我會怎麼做:

(我不是100%肯定它會用Rails 2.3的工作,但它應該,也許可能需要一些調整)

在表單視圖:

<% Country.find(:all).each do |country| %> 
    <%= check_box_tag "channel[country_ids][#{country.id}]", country.id, false, :name => "channel[country_ids][]" %><%= label_tag "country[country_ids][#{country.id}]", country.description %> 
<% end %> 

在模型:

class Channel < ActiveRecord::Base 

    before_create :prepare_for_create 

    attr_accessible :country_ids 


    def prepare_for_create 
    self.country_ids = self.country_ids.join(",") 
    end 
end