【问题标题】:Rails 4: has_one - belongs_to: nested model instance attributes won't assignRails 4:has_one-belongs_to:嵌套模型实例属性不会分配
【发布时间】:2015-01-13 05:36:05
【问题描述】:

我遇到了这个奇怪的问题,其中 instance[:attribute] 用于分配和编写属性,但 instance.attribute、instance.update 等都无法更改模型实例中的属性值。

这是一个用户模型:

class User < ActiveRecord::Base
  has_one :api_account, inverse_of: :user, dependent: :destroy

# Other user-specific validations come after

这里是关联的 api_account:

class ApiAccount < ACtiveRecord::Base
  belongs_to :user, inverse_of: :api_account
  validates :access_token, presence: true
  validates :user, presence: true,
                   uniqueness: true

在 api_account 控制器中,我有:

response = ### Some JSON response from a distant server

@api_account = @user.create_api_account(:access_token => response[:access_token])
# -> This doesn't work and does not set the access_token attribute in the database.
# id: 2, access_token: nil, user_id: nil, created...

然后我将其更改为@api_account = @user.build_api_account(:access_token =&gt; response[:access_token]),然后是user_id: 1,但access_token: nil

在 Rails 控制台中:@a = @u.build_api_account 有效,@a[:access_token] = "access_token" 有效,并且保存保留该更改。但我尝试的其他一切都失败了。

注意:@a.access_token = "access_token",仅更改 @a.access_token 的属性;但是检查@a 仍然显示“access_token 属性是nil

api_account 的架构如下所示:

create_table "api_accounts", force: true do |t|
  t.text     "access_token"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "user_id"
end

add_index "api_account", ["user_id"], name: "index_api_accounts_on_user_id"

有人知道这里出了什么问题吗?用户实例工作正常 - 正常的属性操作工作得很好。我完全迷路了。 “has_one”有一些不同之处,并且没有像“has_many”那么多的文档。

【问题讨论】:

    标签: ruby-on-rails ruby belongs-to has-one


    【解决方案1】:

    我猜这是一个批量分配问题。

    你需要传递允许的参数。

    请检查此链接。

    http://blog.trackets.com/2013/08/17/strong-parameters-by-example.html

    【讨论】:

    • 我花时间阅读了那篇文章并在控制器中实现了params = ActionController::Parameters.new(api_account: response)。但是,我似乎无法传递错误消息:“参数丢失或值为空”。想法?
    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多