Rails 3:未设置虚拟属性

时间:2013-02-02 16:32:00

标签: ruby-on-rails nested-forms virtual-attribute

我有以下User模型,其中包含artist_attributes虚拟属性:

class User < ActiveRecord::Base
  attr_accessor :artist_attributes
  attr_accessible :artist_attributes

  belongs_to :artist
  accepts_nested_attributes_for :artist, update_only: true
end

以下是艺术家模型:

class Artist < ActiveRecord::Base
  has_one :user
end

问题是没有设置虚拟属性。例如,这是我的用户控制器:

class Members::UsersController < Members::BaseController
  def update
    current_user.artist_attributes = params[:user].delete(:artist_attributes)
    p current_user.artist_attributes # => nil
    # ...
  end
end

以下是提交的表单:

<%= simple_form_for current_user, url: members_profile_path do |f| %>
  <%= f.simple_fields_for :artist do |ff| %>
    <%# ... %>
  <% end %>

  <%= f.submit "Edit profile", class: "btn btn-primary", disable_with: "Editing profile..." %>
<% end %>

为什么没有设置artist_attributes虚拟属性?是因为嵌套的形式吗?

更新

提交表单后,这是params哈希:

Parameters: {
  "utf8"=>"✓",
  "authenticity_token"=>"XQI4y7x7CSjxUhdYvEv2bLEjitwCfXxeTBUU3+kYS4g=",
  "user"=> {
    "email"=>"youjiii@gmail.com",
    "forename"=>"You",
    "surname"=>"Jiii",
    "password"=>"[FILTERED]",
    "password_confirmation"=>"[FILTERED]",
    "artist_attributes" => {
      "bio"=>"NERVO is awesome!",
      "phone_number"=>"",
      "city"=>"",
      "country"=>"Afghanistan"
    }
  },
  "commit"=>"Edit profile"}

1 个答案:

答案 0 :(得分:1)

试试这个:

更改

current_user.artist_attributes = params[:user].delete(:artist_attributes)

if current_user.update_attributes(params[:user])
  # happy result
end

嵌套属性应由Rails自动处理。如果您需要自定义设置器,请定义artist_attributes=,您应该很好。我相信Rails 4将支持Postgresql中的哈希值。想看看Rails 3:http://travisjeffery.com/b/2012/02/using-postgress-hstore-with-rails/

修改

根据您的评论,如果目标只是将其发送到您的API,我就不会将其存储在虚拟属性中。

# Controller
def update
  if User.update_artist(params[:user][:artist_attributes])
    # happy thoughts
  end
end

# User model
def update_artist(artist_attributes)
  begin
    # API call
  rescue api exception
    log a message like "Couldn't update at this moment"   
  end
end