2014-09-10 4 views
0

Этот вопрос неоднократно задавался другими пользователями, но до сих пор не решил мою проблему. У меня возникла проблема с моими приложениями rails, где появляется ошибка «Unpermitted Parameters: profile».Неопроверенные параметры: профиль (NestedAttributes) - RAILS 4

user_controller.rb

class Admin::UsersController < ApplicationController 
    before_filter :set_user, only: [:edit, :update] 
    before_filter :store_location, only: [:index] 
    before_filter :require_admin 

    def edit 
    if @user 
     render 
    else 
     redirect_to admin_users_path, notice: "User profile not found." 
    end 
    end 

    def update 
    # Rails.logger.debug "===> (1)" 
    if @user.update(user_params) 
     redirect_to edit_admin_user_path, notice: "#{@user.profile.full_name} account has been updated." 
    else 
     render 'edit' 
    end 
    end 

    private 

    def set_user 
    @user = User.find(params[:id]) 
    end 

    def user_params 
    params.require(:user).permit(:id, :username, :email, profile_attributes: [:user_id, :full_name]) 
    end 
end 

edit.html.erb

<%= form_for :user, url: admin_user_path(@user), method: :patch do |f| %> 

    <div class="form-group"> 
    <%= f.label :username %><br> 
    <%= f.text_field :username, :class => "form-control" %> 
    </div> 

    <%= f.fields_for :profile, @user.profile do |profile| %> 

    <div class="form-group"> 
    <%= profile.label :full_name %><br> 
    <%= profile.text_field : full_name, :class => "form-control" %> 
    </div> 

    <% end %> 

    <div class="form-group"> 
    <%= f.submit "Save", :class => "btn btn-primary" %> 
    </div> 

<% end %> 

User.rb

class User < ActiveRecord::Base 

    has_one :profile 
    accepts_nested_attributes_for :profile #, update_only: true, allow_destroy: true 

    validates :username, :uniqueness => { :case_sensitive => false } 

end 

Profile.rb

class Profile < ActiveRecord::Base 

    belongs_to :user 

    validates_presence_of :user_id 
    validates_presence_of :full_name 

end 

development.log

Started PATCH "/master/users/7" for 127.0.0.1 at 2014-09-10 23:18:26 +0800 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"23oUfOBaYAmcrfhW3R11F1x53lJAT760Shv0HqkmEzw=", "user"=>{"username"=>"lisa", "profile"=>{"full_name"=>"Evalisa Andriaasdasda"}}, "commit"=>"Save", "id"=>"7"} 
[1m[35mUser Load (0.3ms)[0m SELECT `users`.* FROM `users` WHERE `users`.`id` = 7 LIMIT 1 
[1m[36mUser Load (0.3ms)[0m [1mSELECT `users`.* FROM `users` WHERE `users`.`id` = 6 ORDER BY `users`.`id` ASC LIMIT 1[0m 
Unpermitted parameters: profile 
[1m[35m (0.2ms)[0m BEGIN 
[1m[36mUser Exists (0.4ms)[0m [1mSELECT 1 AS one FROM `users` WHERE (`users`.`username` = 'lisa' AND `users`.`id` != 7) LIMIT 1[0m 
[1m[35m (0.2ms)[0m COMMIT 
[1m[36mProfile Load (0.4ms)[0m [1mSELECT `profiles`.* FROM `profiles` WHERE `profiles`.`user_id` = 7 LIMIT 1[0m 

Я действительно не знаю, где ошибка. Пожалуйста помоги.

Заранее благодарен!

ответ

2

Обновите свой метод user_params, чтобы включить все атрибуты из объекта профиля. У вас не хватает id поэтому рельсы пытается создать объект профиля, и это вызывает нежелательное поведение (Ваш журнал развития показывает, вы делаете запрос PATCH, так что вы пытаетесь обновить что-то, а не создавать что-то):

def user_params 
    params.require(:user).permit(:id, :username, :email, profile_attributes: [:id, :user_id, :full_name]) 
end 

Вам также может потребоваться обновить форму, чтобы фактически передать id объекта profile.

Смотрите этот ответ на другой вид: https://stackoverflow.com/a/17561608/1026898

2

Ах, я решил свой вопрос. Для тех, кто там, вот решение: -

Из development.log, я замечаю что-то "profile" => {}. Это должно быть "profile_attributes" => {} так что я изменил мой edit.html.erb формы: -

<%= form_for :user, url: admin_user_path(@user), method: :patch do |f| %> 

    <div class="form-group"> 
    <%= f.label :username %><br> 
    <%= f.text_field :username, :class => "form-control" %> 
    </div> 

    <%= f.fields_for :profile_attributes, @user.profile do |profile| %> 

    <div class="form-group"> 
    <%= profile.label :full_name %><br> 
    <%= profile.text_field :full_name, :class => "form-control" %> 
    </div> 

    <% end %> 

    <div class="form-group"> 
    <%= f.submit "Save", :class => "btn btn-primary" %> 
    </div> 

<% end %> 

Тогда я сказал другой ошибка в development.log: -

ActiveRecord::RecordNotSaved (Failed to remove the existing associated profile. The record failed to save after its foreign key was set to nil.): 

Итак, еще раз, я обновить мою user.rb иметь: -

class User < ActiveRecord::Base 

    has_one :profile 
    accepts_nested_attributes_for :profile, update_only: true, allow_destroy: true 

    validates :username, :uniqueness => { :case_sensitive => false } 
end 
Смежные вопросы