我是 Ruby on Rails 和网络编程的新手。在我的应用程序中,我有两个模型;Directorate whichhas_many :users
和 User which belongs_to :directorate
。创建新用户时,我使用<%= f.collection_select(:directorate_id,Directorate.all, :id, :name) %>
new.html.erb 表单将新用户分配给特定的董事会。但是,我想为列出所有董事的 dba 构建一个用户友好的界面;并在每个董事会旁边列出所有用户,并带有一个链接,可以将任何用户分配到特定的董事会。
我所做的是以下内容:
在 Directorate 模型中,我定义了以下函数:
def assign_user!(user)
user.update_attributes(directorate_id: @directorate)
end
在董事会控制器中,我定义了以下操作:
def assign_user
@directorate = params[:directorate]
assign_user! params[:user]
redirect_to directorates_url
end
现在,directates/index.html.erb 包含以下内容:
<h1>Listing directorates</h1>
<table>
<tr>
<th>Name</th>
<th>Info</th>
</tr>
<% @directorates.each do |directorate| %>
<tr>
<td><%= directorate.name %></td>
<td><%= directorate.info %></td>
<td><%= link_to 'Show', directorate %></td>
<td><%= link_to 'Edit', edit_directorate_path(directorate) %></td>
<td><%= link_to 'Destroy', directorate, confirm: 'Are you sure?', method: :delete %></td>
<%= @directorate = directorate%>
<%= render 'users_form' %>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Directorate', new_directorate_path %>
并且,-users_form.html.erb 包含以下表单(应该列出每个部门旁边的所有用户,并带有将任何用户分配到某个部门的链接):
<h1>Listing Users</h1>
<table>
<tr>
<th>User Name</th>
</tr>
<% @users.each do |user| %>
<tr>
<td><%= user.username %></td>
<td><%= link_to 'Assign to Current Directorate', {controller: 'directorates', action: 'assign_user', directorate: @directorate, user: user}, :method => :put %></td>
</tr>
<% end %>
</table>
<br />
这是问题所在,当列出董事会并单击“分配给当前董事会”时,我收到以下错误:
http://127.0.0.1:3000/directorates/assign_user?directorate=4&user=5
ActiveRecord::RecordNotFound in DirectoratesController#update
Couldn't find Directorate with id=assign_user
Rails.root: /home/ehab/sites/IAMS
Application Trace | Framework Trace | Full Trace
app/controllers/directorates_controller.rb:61:in `update'
Request
Parameters:
{"_method"=>"put",
"authenticity_token"=>"L5tz3hv2IW0meE79qUq0/tjfGKwDlpC23hOeAWtmTvk=",
"directorate"=>"4",
"user"=>"5",
"id"=>"assign_user"}
很明显,参数正在提交我不想要的“id”=>“assign_user”,我想要的是“id”=>“directorate.id”(上例中的 4)。我该怎么做才能解决这个问题?!