2014-01-19 48 views
2

在我的Rails 4控制器的動作,我傳遞了以下PARAMS創建兩個對象:Rails中4控制器strong_params

{"user"=>{"email"=>"", "password"=>"[FILTERED]", "profile"=>{"birthday"=>nil, "gender"=>nil, "location"=>"", "name"=>""}}} 
從這些PARAMS

現在我希望建立兩個對象:User及其Profile

我試過下面的代碼的重複,但不能獲得通過strong_params問題:

def create 
    user = User.new(user_params) 
    profile = user.build_profile(profile_params) 

    ... 
end 

    private 

    def user_params 
     params.require(:user).permit(:email, :password) 
    end 

    def profile_params 
     params[:user].require(:profile).permit(:name, :birthday, :gender, :location) 
    end 

由於上面的代碼中拋出一個Unpermitted parameters: profile錯誤,我想知道,如果profile_params方法,甚至曾經讓擊中。它幾乎感覺我需要在user_paramsprofile並處理該問題。我已經試過了,以及,我strong_params方法更改爲:

def create 
    user = User.new(user_params) 
    profile_params = user_params.delete(:profile) 
    profile = user.build_profile(profile_params) 

    ... 
end 

private 

    def user_params 
    params.require(:user).permit(:email, :password, profile: [:name, :birthday, :gender, :location]) 
    end 

,但我得到ActiveRecord::AssociationTypeMismatch - Profile(#70250830079180) expected, got ActionController::Parameters(#70250792292140):

任何人都可以闡明這一些輕?

回答

3

試試這個:

user = User.new(user_params.except(:profile)) 
profile = user.build_profile(user_params[:profile]) 

你也可以使用Rails' nested attributes。在這種情況下,配置文件參數將嵌套在密鑰:profile_attributes中。

+0

啊,除了不知道。謝謝! – tvalent2

4

這無疑是一個嵌套參數應該使用的時間。

你應該做以下修改:

型號:

class User < ActiveRecord::Base 
    has_one :profile 
    accepts_nested_attributes_for :profiles, :allow_destroy => true 
end 

class Profile < ActiveRecord::Base 
    belongs_to :user 
end 

用戶控制器:

def user_params 
    params.require(:user).permit(:email, :password, profile_attributes: [:name, :birthday, :gender, :location]) 
end #you might need to make it profiles_attributes (plural) 

在表單視圖,請務必使用fields_for方法爲您的配置文件的屬性。

+0

使用嵌套屬性絕對有效。感謝那裏的提醒。 – tvalent2