在我的rails 4应用中,我有一个user
模型has_one
profile
模型belongs_to
user
模型
这是我第一次使用嵌套资源,所以我有点失去它 怎么样 ,用户创建帐户,在成功进行电子邮件身份验证后,用户继续创建配置文件。问题是,我在使用build_association时遇到错误。我不确定问题是否实际上是或者我在params上得到空值(我认为没有)
在我的routes.rb
中resources :users do
resources :profiles
end
个人资料视图,new.html.erb
<%= form_for(@profile,url:{ :controller => 'profiles', :action => 'create'},html: {class: "ui large segment form error"}) do |f| %>
<%= render 'shared/form_error_messages', object: f.object%>
<div class="ui horizontal divider">Create a Profile</div>
<%= f.text_field :first_name, :placeholder => "First Name" , :required => true%>
<%= f.submit "Submit Profile", class: "ui submit button"%>
<% end %>
profiles_controller.rb
def new
@user = User.find(params[:user_id])
@profile = @user.build_profile
end
def create
@profile = @user.build_profile(profile_params)
if @profile.save
flash[:success] = "Profile has been created"
redirect_to root_url
else
render 'new'
end
end
private
def profile_params
params.require(:profile).permit(:first_name)
end
当我提交表单时,我正在
NoMethodError in ProfilesController#create
undefined method `build_profile' for nil:NilClass
Application Trace | Framework Trace | Full Trace
app/controllers/profiles_controller.rb:9:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"MFCANYra..",
"profile"=>{"first_name"=>"sample",
"commit"=>"Submit Profile",
"user_id"=>"1"}
答案 0 :(得分:0)
尝试更改profiles_controller.rb中的创建操作,如下所示: -
def create
@user = User.find(params[:profile][:user_id])
@profile = @user.build_profile(profile_params)
if @profile.save
flash[:success] = "Profile has been created"
redirect_to root_url
else
render 'new'
end
end
让我知道这是否有效,试着找出是否有其他因素导致问题,谢谢。