2016-06-14 41 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

相關問題