2011-01-29 70 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