![](/img/trans.png)
[英]How do I redirect_to a newly rendered page (not cached) in Rails?
[英]How do I change the form rendered by Rails?
我有两个类,用户和联系人。 一个用户有许多联系人,而一个联系人属于该用户。 在用户的显示视图中,我有:
<%= link_to 'Add Contact', :controller => "contacts", :action => "new", :user => @user.id %>
然后,在联系人的控制器中,在新动作下,我有:
@user = User.find(params[:user])
@contact = Contact.new
@contact.user = @user
呈现新的联系表单时,它在“用户”字段中已经有#<User:0x4c52940>。 但是,当我提交表单时,出现错误:User(#39276468),String(#20116704)。
问题在于,当调用create时,Ruby将采用表单中的所有内容并覆盖新Contact中的字段。 因此:如何更改表单以删除“用户”字段,以使用户不会被字符串覆盖?
编辑:我的联系人的new.html.erb具有:
<%= render 'form' %>
<%= link_to 'Back', contacts_path %>
联系人的控制器:
def new
@user = User.find(params[:user])
@contact = Contact.new
@contact.user = @user
respond_to do |format|
format.html # new.html.erb
format.json { render json: @contact }
end
end
和
def create
@contact = Contact.new(params[:contact])
respond_to do |format|
if @contact.save
format.html { redirect_to @contact, notice: 'Contact was successfully created.' }
format.json { render json: @contact, status: :created, location: @contact }
else
format.html { render action: "new" }
format.json { render json: @contact.errors, status: :unprocessable_entity }
end
end
end
我相信您滥用控制器的创建动作。 本质上它的内容应该像这样
def create
@user = User.find(params[:user_id])
contact = @user.contacts.build(params[:contact])
if contact.save
flash[:alert] = 'New contact is created'
redirect_to contacts_path(contact)
else
flash.now[:error' = 'Error creating contract'
render :action => :new
end
end
因此,+ 1为上一个答案-向您显示控制器和新的表单代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.