【问题标题】:Creating two objects in Rails 4 controller with strong_params使用 strong_params 在 Rails 4 控制器中创建两个对象
【发布时间】:2014-01-19 20:09:40
【问题描述】:

在我的 Rails 4 控制器操作中,我传递了以下参数:

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

现在我希望从这些参数中创建两个对象: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_params 中要求profile 并处理它。我也尝试过,将我的 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):

有人能解释一下吗?

【问题讨论】:

    标签: ruby-on-rails-4 strong-parameters


    【解决方案1】:

    毫无疑问,此时应该使用嵌套参数。

    您应该进行以下更改:

    型号:

    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 方法。

    【讨论】:

    • 使用嵌套属性绝对有效。感谢那里的提醒。
    【解决方案2】:

    试试这个:

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

    您也可以使用Rails' nested attributes。在这种情况下,配置文件参数将嵌套在键 :profile_attributes 中。

    【讨论】:

    • 啊,不知道除了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多