collection_select选定的值

时间:2009-08-11 10:36:23

标签: ruby-on-rails

我在一个页面上有两个相同的collection_selects(一个消息属于2个组)

<%= 
collection_select(:message,:group_ids, Group.find(:all),:id, :title, {}, {:name=>'message[group_ids][]'} ) 
%>
<%= 
collection_select(:message,:group_ids, Group.find(:all),:id, :title, {}, {:name=>'message[group_ids][]'} ) 
%>

是否可以使用collection_select为其设置两个不同的选定值?

修改

我想我必须做类似

的事情
<%
@message.group_id=5
%>
<%= 
collection_select(:message,:group_id, Group.find(:all),:id, :title, {}, {:name=>'message[group_ids][]'} ) 
%>
<%
@message.group_id=6
%>
<%= 
collection_select(:message,:group_id, Group.find(:all),:id, :title, {}, {:name=>'message[group_ids][]'} ) 
%>

但当然它不起作用并且方法缺少错误

EDIT2

猜猜没有办法用collection_select来做。除非group有一个方法,每次都返回一个group_id。

我最终得到的是

 select_tag 'message[group_ids][]', "<option></option>"+options_from_collection_for_select(Group.find(:all), 'id', 'title',group1.id)
 select_tag 'message[group_ids][]', "<option></option>"+options_from_collection_for_select(Group.find(:all), 'id', 'title',group2.id)

1 个答案:

答案 0 :(得分:5)

您需要设置模型和关系,如下所示:

class Message < ActiveRecord::Base  
  has_many :message_groups   
  has_many :groups, :through => :message_groups  
  accepts_nested_attributes_for :message_groups  #Note this here! 
end

class Group < ActiveRecord::Base
  has_many :message_groups
  has_many :messages, :through => :message_groups
end

class MessageGroup < ActiveRecord::Base
  belongs_to :group
  belongs_to :message
end

然后在你的表格中......

<% form_for(@message) do |f| %>
  <%= f.error_messages %>
    <% f.fields_for :message_groups do |g| %>
    <p>
        <%= g.label :group_id, "Group" %>
        <%= g.select :group_id, Group.find(:all).collect {|g| [ g.title, g.id ] } %>
    </p>
    <% end %>
  <p>
    <%= f.submit 'Update' %>
  </p>
<% end %>

这是我的完整性迁移

class CreateGroups < ActiveRecord::Migration
  def self.up
    create_table :groups do |t|
      t.string :title
      t.timestamps
    end
  end

  def self.down
    drop_table :groups
  end
end

class CreateMessages < ActiveRecord::Migration
  def self.up
    create_table :messages do |t|
      t.text :body
      t.timestamps
    end
  end

  def self.down
    drop_table :messages
  end
end


class CreateMessageGroups < ActiveRecord::Migration
  def self.up
    create_table :message_groups do |t|
      t.integer :message_id
      t.integer :group_id
      t.timestamps
    end
  end

  def self.down
    drop_table :message_groups
  end
end

希望这有助于......!