collection_select выбранное значение - PullRequest
1 голос
/ 11 августа 2009

У меня есть две идентичные коллекции collection_select на одной странице (одно сообщение, принадлежащее двум группам)

<%= 
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_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 Ответ

5 голосов
/ 13 августа 2009

Вам нужно настроить свои модели и отношения следующим образом:

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

Надеюсь, это поможет ...!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...