【发布时间】:2013-05-07 03:07:34
【问题描述】:
在我的 Rails 应用程序中,我需要在表单中显示带有复选框的用户电子邮件 ID,以将用户分配到特定项目。我有一个数组对象@programmers,对象中的每一行都包含电子邮件ID,我需要在表单中用复选框显示。
我的包含表单的部分视图是:
_allocate_programmer.html.erb
<h1> Allocate programmers </h1>(Please check the programmers that you want to add)<br />
<%= form_for(@project) do |f| %>
<% if @project.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@project.errors.count, "error") %> prohibited this project from being saved:</h2>
<ul>
<% @project.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<% unless @programmers.nil? %>
<% @programmers.each do |programmer| %>
<%= f.check_box :programmer, programmer.email %>
<% end %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我的 routes.rb 有:
匹配 'projects/:id/allocate_programmers' => 'projects#allocate'
我的 projects_controller.rb 有以下代码:
def allocate
@project = Project.find(params[:id])
@programmers = User.where(:role => 'programmer')
render "_allocate_programmer"
end
我在视图中收到以下错误
NoMethodError in Projects#allocate
Showing /home/local/Rajesh/ticket_system/app/views/projects/_allocate_programmer.html.erb where line #18 raised:
undefined method 'merge' for "test@gmail.com":String
我认为这是复选框哈希的问题。请帮忙。
用户.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :token_authenticatable,
:rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :role
# attr_accessible :title, :body
has_many :assignments
has_many :projects, :through => :assignments
has_many :tickets
ROLES = ['admin', 'network/system admin', 'manager', 'programmer']
def role?(base_role)
ROLES.index(base_role.to_s) <= ROLES.index(role)
end
end
Project.rb
class Project < ActiveRecord::Base
attr_accessible :project_name, :description, :duration_from, :duration_upto, :user_id
has_many :assignments
has_many :users, :through => :assignments
validates :project_name, :presence => true
validates :description, :presence => true
validates :duration_from, :presence => true
validates :duration_upto, :presence => true
#validates :user_id, :presence => true //this gives error
end
Assignment.rb
class Assignment < ActiveRecord::Base
attr_accessible :user_id, :project_id
belongs_to :user
belongs_to :project
end
请检查。我用 3 个模型更新了问题。
【问题讨论】:
-
您是否充分设置了
Project和Programmer之间的HABTM 关系? -
没有。我只设置了HM关系。并通过另一个称为 assignments 的模型连接 Project 和 Programmer,因为一个项目可以有多个程序员,反之亦然。
-
你的意思是,
has_many :programmers, :through => :assignments? -
是的。当然,反之亦然
-
准确地说,在关联中使用复选框是一种错误的方式。您正在迭代中生成复选框,并使用
:programmer就好像它是Project模型的属性一样。此操作会将您带到不知道如何处理的update操作。
标签: ruby-on-rails activerecord checkbox