代码之家  ›  专栏  ›  技术社区  ›  Pavel K.

集合\选择所选值

  •  1
  • Pavel K.  · 技术社区  · 15 年前

    我在一页上有两个相同的集合(一条消息属于两个组)

    <%= 
    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][]'} ) 
    %>
    

    是否可以使用集合“选择”为它们设置两个不同的选定值?

    编辑 :

    我想我得做点什么

    <%
    @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][]'} ) 
    %>
    

    但它当然不起作用,给方法带来了误差

    编辑2 :

    我想没有办法选择收藏。除非组有方法,否则每次返回单个组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 回复  |  直到 15 年前
        1
  •  5
  •   Chalkers    15 年前

    您需要像这样建立模型和关系:

    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
    

    希望这有帮助…!