使用具有accepts_nested_attributes_for形式的collection_select来生成多对多关系

问题描述

| 新的Rails开发人员在这里尝试学习有关活动记录关联的方法。 我正在构建一个事件调度应用程序,并且正在使用邀请功能。我已经有了基本的“何时/何地”事件创建表单,现在我想为事件创建者提供一种方法,以从站点上创建者的朋友(朋友)列表中生成被邀请参加该事件的用户列表由自反的has_many:通过User模型上的友谊关系记录)。我建立了一个has_many:through邀请模型来表示事件和用户(被邀请者)之间的多对多关系。各个模型如下所示: User.rb
class User < ActiveRecord::Base

      has_many :friendships
      has_many :friends,:through => :friendships

      attr_accessor :password
      attr_accessible :first_name,:middle_name,:last_name,:email,:password,:password_confirmation

      has_many :events

      has_many :invitations,:foreign_key => :invitee_id
      has_many :inviting_events,:through => :invitations,:source => :event

end
Event.rb
class Event < ActiveRecord::Base

  attr_accessible :title,:description,:location,:time_start,:time_end,:event_access_type

  belongs_to :user

  has_many :invitations
  has_many :invitees,:through => :invitations

  accepts_nested_attributes_for :invitations

end
Friendship.rb
class Friendship < ActiveRecord::Base

  belongs_to :user
  belongs_to :friend,:class_name => \"User\"

end
Invitation.rb
class Invitation < ActiveRecord::Base

  belongs_to :event
  belongs_to :invitee,:class_name => \"User\"

end
我要尝试使用的表单是生成一个下拉列表,其中启用了多项选择(我知道这是糟糕的UI,但这仅是为了进行测试和进行原型设计),该列表填充了当前用户的好友现场。为此,我目前正在使用此表单帮助器方法
<%= collection_select(:friendship,:friend_id,current_user.friendships,:friends_name,{},html_options = {:multiple => true}) %>
这会生成一个下拉列表,我要提交事件创建者想要邀请的用户的friend_id(即user_id)。我的下一步是在提交时进行这些选择,并使用每个friend_id值在生成的事件和朋友之间生成新的邀请关联。我的理解是,由于这是一种多模型形式,因此我需要在事件模型中包含\“ accepts_nested_attributes_for:invitations \”。我的基本问题是,我不清楚应采用哪种形式和控制器语法来获取提交的下拉值,并使用它们生成新的邀请对象。这是我在表单视图中的最新尝试: _event.form.html.erb
<%= form_for(@event) do |f| %>
  <%= render \'shared/error_messages\',:object => f.object %>
  <div class=\"field\">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class=\"field\">
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  </div>
  <div class=\"field\">
    <%= f.label :location %><br />
    <%= f.text_field :location %>
  </div>
    <% f.fields_for :invitation do |invitation_form| %>
        <div class=\"field\">
            <%= invitation_form.label \"Who\'s invited?\" %><br />
            <%= collection_select(:friendship,html_options = {:multiple => true}) %>
        </div>
    <% end %>
  <div class=\"actions\">
    <%= f.submit \"Submit\" %>
  </div>
<% end %>
如果有人可以提供有关如何完成此操作的指导,以及我在使用的关系或表格方法方面犯了任何错误,将不胜感激。 谢谢!     

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...