Country has_many Channels select checkboxes
I feel like this should be simple but I'm having issues getting it to work. I've tried HABTM but I don't think it's what I need.
A 'Country' has_many 'Channels' and a 'Channel' belongs_to a 'Country'. Basically I want to list the countries with checkboxes on the channels form and have it save an array of countries in the country_id.
Here's the view:
<%= 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
I'm going to be doing the same thing with satellites, statistics, testimonies, and videos as well.
Any help is appreciated. Thanks!
FYI I'm doing this in Rails 2.3.8 and not Rails 3.
If you mean that you want to store a list of country id's in a string field in the channels table, this is how I would do it:
(I'm not a 100% sure it would work in Rails 2.3, but it should, maybe a little tweaking may be needed)
In form view:
<% 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 %>
In model:
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
You say:
save an array of countries in the country_id
When you specify country_id on Channel it means that the channel belongs to one country. It sounds more like you want a channel to have many countries though...perhaps it's a M:M relationship you want? Either way, you can't "save an array" to country_id or any field on a model...at least not for what you're trying to accomplish.
Also, belongs_to :countries
should be belongs_to :country
精彩评论