2016-06-14 55 views
0

对于我的生活,我不知道发生了什么。我正在使用Rails 5和React。我似乎无法更新我的个人资料。无法用update_attributes更新用户配置文件

更新路由:

/users/:user_id/profile(.:format) profiles#update 

在我的反应成分,形式是:

<form data-abide="" encType="multipart/form-data" action={url} method="patch"> 
    <input type="text" name="profile[first_name]" value={this.state.firstName}/> 
    <button className="button expanded" type="submit">Update</button> 
</form> 

如果我设置表单方法为 “后”,这是不言而喻的create方法并替换我不需要的列,所以我将其更改为patch

档案控制器:

... 
skip_before_filter :verify_authenticity_token # The only way to get this to work with React 


def create 
    @profile = current_user.build_profile(profile_params) 
    if @profile.save 
    #... 
    else 
    #... 
    end 
end 

def update 
    @profile = current_user.profile 
    if @profile.update_attributes(profile_params) 
    #... 
    else 
    #... 
    end 
end 

private 
def profile_params 
    params.require(:profile).permit(:first_name) 
end 

... 

有什么错吗?

编辑:

我得到它的工作,我的表格方式设置为post则:

def create 
    update 
end 

是否有一种方式来获得的形式直接调用update方法?在注释中,表单只支持GET/POST而不是PATCH。

+0

你是什么意思*无法更新*。你的代码是否会引发错误?什么错误和哪里? – spickermann

+0

@spickermann嗨。没有错误。即使在控制台中也没有。更新以更新字段。说我想改变我的名字,它不会改变。 – Sylar

+1

日志说什么?行动是否被称为? SQL执行(并回滚了吗?)您是否试图从纯HTML表单或CURL调用控制器? –

回答

0

如果您将配置文件定义为路由文件中的资源,则可以从窗体访问此资源。

型材/ edit.html.erb

<%= form_for @profile do |f| %> # Additionally can add method: :patch 
# your fields 
<% end %> 

在控制器

def edit 
    @profile = current_user.profile 
end 

def update 
    @profile = Profile.find(params[:id]) 
    if @profile.update_attributes(profile_params) 
    flash[:notice] = "Your profile has been saved!" 
    render some page 
    else 
    flash[:notice] = "Your profile has not been saved!" 
    render or redirect some page 
    end 
end 

在我看来,你应该检查一下您的个人资料是否正确更新。使用

@profile.errors 

希望这会有所帮助。

+0

感谢您的回答,但请阅读我的文章。我正在使用我的表单反应,而不是'erb'。 – Sylar

+0

@Sylar,哦,对不起。您应该检查您的表单是否正在请求更新操作,并且该配置文件是否正确更新。您也可以尝试使用控制台执行update_attributes。 – MaruniakS