在我的应用程序中,我有3个类似的模型:
class Person
has_many :groups
has_many :group_memberships, :foreign_key => "member_id"
end
class Group_Membership
belongs_to :member, :class_name => 'Person'
belongs_to :group
end
class Group
belongs_to :person
has_many :group_memberships
has_many :members, :class_name => "Person", :through => "group_memberships", :foreign_key => "member_id"
我需要的是在组#show页面中创建一个按钮,允许Person要求group_membership。根据上一个问题的建议,我在Group_Membership控制器上发了def create_membership
:
def create_membership
@group = Group.find params[:id]
if @group.group_memberships.create( :member_id => params[:member_id])
redirect_to @group
else
render :action => 'show'
end
end
所以我转到了我的表单,在#show view组中,我做了如下:
<%= form_for :group_membership, @group_membership, :url => { :action => "create_membership" } do |f| %>
<%= submit_tag "Create" %>
<% end %>
但每次我点击按钮,它都会将我重定向到表单以创建新组,而不是Group_Membership。任何提示? 提前谢谢。
######## EDIT ##########
好吧,我有点改变了我的代码:
def create
@person = Person.find(current_person)
@group = Group.find(params[:group_id])
params[:group_membership] = {:member_id => @person.id, :group_id => @group.id}
@group_membership = Group_Membership.create(params[:group_membership])
if @group_membership.save
redirect_to @person
else
redirect_to @person
end
end
我的表格现在就是这样:
<% form_for(:group_membership, :url => group_memberships_path(:member_id => current_person, :group_id => @group.id)) do |f| %>
<%= submit_tag "Join!" %>
现在我可以实际创建group_membership模型,但这两个id在数据库列member_id
和group_id
中都是空白的。
如果我将行@group_membership = Group_Membership.create(params[:group_membership])
更改为@group_membership = Group.Group_Membership.create(params[:group_membership])
,我就可以保存组ID。如果我改为Person.
,也一样。
答案 0 :(得分:0)
只是为了清理一下
def create
@group_membership = Group_Membership.create(:group => Group.find(params[:group_id]), :member => Person.find(current_person))
if @group_membership.save
redirect_to @person
else
redirect_to @person
end
end
此代码应该在rails 3中工作我不确定早期版本