【发布时间】:2011-05-16 21:07:21
【问题描述】:
我有两个模型,组和用户
用户 belongs_to 组和 组 has_many 用户
在我的组/show.html.erb 中,我有用户注册表单
<h1>Create user</h1>
<%= form_for @user do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :password %><br />
<%= f.password_field :password %>
</div>
<div class="field">
<%= f.label :password_confirmation, "Confirmation" %><br />
<%= f.password_field :password_confirmation %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
为了获得组和用户之间的关系,我在用户控制器中有一个 create 方法,如下所示
def create
@group = Group.find(params[:group][:id])
@user = @group.users.build(params[:user])
if @user.save
flash[:success] = "You have created a new user"
redirect_to group_path
else
@title = "Create user"
render 'new'
end
end
我也试过: @group = Group.find(params[:id])
和
@group = Group.find(params[:group_id])
但我仍然收到错误
基本上我想在 group/show.html.erb 中创建新用户并将该用户与创建用户的组相关联。例如,如果用户是在 groups/3 中创建的,我如何在 Users 控制器中设置我的创建方法以确保这种关系成立?
总的来说,我一直在关注http://ruby.railstutorial.org/chapters/user-microposts#sec:creating_microposts 上的 Hartl Rails 教程,并遵循表单和创建方法的方法。但是我不确定如何将 groups/3 的参数放入 find 方法中,例如 @group = Group.find(?????)
谁能赐教,这个问题困扰我好几天了。
提前致谢
【问题讨论】:
-
我感觉我可能需要在表单中使用 hidden_field_tag 来传递 group.id 但不知道该怎么做