Ruby on rails не будет обновлять атрибуты модели профиля - PullRequest
1 голос
/ 08 января 2012

В моей пользовательской модели обновление работает отлично ... Независимо от того, что я делаю в моей модели профилей, представление контроллера не обновит мою базу данных. В моей пользовательской модели я столкнулся с той же проблемой, но обнаружил, что мне нужно поле для ввода пароля. В этом, однако, я этого не делаю, так как в модели профиля не установлено никакой проверки.

Понятия не имею, что происходит. Журналы в терминале показывают, что current_user.id находится, и я использую этот результат, чтобы найти user_id в моей таблице профилей, и это работает. Обновление не произойдет, хотя.

Что может быть не так?

С уважением

Журналы

--- &id001 !ruby/object:Profile 
_already_called: 
  ? 
    - :autosave_associated_records_for_user
    - :user
  : false

_start_transaction_state: 
  :id: 1
  :new_record: false
  :destroyed: false
  :level: 1
aggregation_cache: {}

association_cache: {}

attributes: 
  id: 1
  user_id: 1
  motd: Success is guaranteed!
  first_name: Foo
  last_name: Bar
  birthday: 
  star_sign: 
  gender: 
  marital_status: 
  sexual_preference: 
  racial_background: 
  location: 
  profile_url: 
  about_me: 
  height: 
  body_type: 
  eye_colour: 
  drugs: 
  alcohol: 
  cigarettes: 
  likes: 
  dislikes: 
  bad_habits: 
  food: 
  music: 
  television: 
  book: 
  animal: 
  place: 
  possesion: 
  profile_visits: 
  created_at: 2012-01-07 23:02:29.228500
  updated_at: 2012-01-07 23:02:29.228500
attributes_cache: 
  birthday: 
  created_at: 2012-01-07 23:02:29.228500 Z
  updated_at: 2012-01-07 23:02:29.228500 Z
changed_attributes: {}

destroyed: false
errors: !ruby/object:ActiveModel::Errors 
  base: *id001
  messages: !omap 
    - :motd: []

    - :first_name: []

    - :last_name: []

marked_for_destruction: false
new_record: false
previously_changed: !map:ActiveSupport::HashWithIndifferentAccess {}

readonly: false
relation: 
validation_context: 
Profile updated
--- !map:ActiveSupport::HashWithIndifferentAccess 
utf8: "\xE2\x9C\x93"
_method: put
authenticity_token: YZwwOx5CqfKTfsybXE4NH2o2dTg4asKZZu6QOR9Y3Zo=
profile: !map:ActiveSupport::HashWithIndifferentAccess 
  motd: Success is guaranteed!
  first_name: Foo
  last_name: Bar
commit: update
action: update
controller: profiles
id: "1"

Маршруты

  resources :users
  resources :sessions
  resources :passwords
  resources :profiles


  root :to                   => "users#new"
  match 'success'            => "users#success"
  match 'login'              => "sessions#new"
  match 'logout'             => "sessions#destroy"
  match 'reset_password'     => "passwords#new"
  match 'setup_new_password' => "passwords#edit"
  match 'settings', :to      => "users#settings"


  match "/settings/account", :to => "users#account"
  match "/settings/edit_profile", :to => "profiles#edit_profile"


  match '/:username', :controller => 'users', :action => 'show'

Модель

class Profile < ActiveRecord::Base

  belongs_to :user

   attr_accessible :first_name, :last_name, :motd


end

Profiles_controller

    def new
    @user = Profile.new 
    end

    def update
        @user = Profile.find_by_user_id(current_user.id)
        if @user.update_attributes(params[:user])
        render 'edit_profile'
        flash[:success] = "Profile updated" 
        else
        redirect_to root_path
        end
      end

  def edit

  end

  def edit_profile
  @user = Profile.find_by_user_id(current_user.id)
  end

end

Посмотреть

<div id="formo"> <%= form_for @user,  do |f| %>

<%= f.text_field :motd, :placeholder => "motd"  %><br />
<%= f.text_field :first_name, :placeholder => "fname"  %><br />
<%= f.text_field :last_name, :placeholder => "lname"  %><br />

<%= f.submit 'update' %><br />
<% end %>
<%= debug(@user) %>
<div class="notify">
    <% flash.each do |name, msg| %>
          <%= content_tag :div, msg, :class => "#{name}" %>
    <% end %>
</div>

</div>

1 Ответ

2 голосов
/ 08 января 2012

Изменение:

if @user.update_attributes(params[:user])

На:

if @user.update_attributes(params[:profile])

Также вы можете переименовать эту переменную экземпляра в @profile, чтобы не запутаться.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...