0

我有以下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虚拟属性?是因为嵌套形式吗?

更新

这是我提交表单后的参数哈希:

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"}
4

1 回答 1

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
于 2013-02-02T17:14:03.713 回答