【发布时间】:2011-10-25 06:12:46
【问题描述】:
我有一个这样的 Artist 模型:
# app/models/artist.rb
class Artist < ActiveRecord::Base
# Relationships
has_many :releases
has_many :songs, :through => :releases
has_many :featured_songs, :through => :releases,
:class_name => "Song",
:source => :song,
:conditions => { 'releases.featured', true }
end
检索 features_songs 非常有效。这里的问题是我无法向艺术家添加新的 features_song,因为出于某种原因,“featured”属性设置为“nil”。
这就是我正在尝试的:
ruby-1.9.2-p180 :004 > a = Artist.first
ruby-1.9.2-p180 :005 > a.featured_songs.create(:title => "Title", :user => User.first)
这样的实际结果是:
ruby-1.9.2-p180 :004 > a = Artist.first
ruby-1.9.2-p180 :005 > a.featured_songs.create(:title => "Title", :user => User.first)
User Load (0.9ms) SELECT `users`.* FROM `users` LIMIT 1
SQL (1.0ms) BEGIN
SQL (5.5ms) INSERT INTO `songs` (`created_at`, `title`, `updated_at`, `user_id`) VALUES (?, ?, ?, ?) [["created_at", Thu, 11 Aug 2011 18:30:34 UTC +00:00], ["title", "Title"], ["updated_at", Thu, 11 Aug 2011 18:30:34 UTC +00:00], ["user_id", 1]]
SQL (1.2ms) INSERT INTO `releases` (`album_id`, `artist_id`, `created_at`, `featured`, `song_id`, `updated_at`) VALUES (?, ?, ?, ?, ?, ?) [["album_id", nil], ["artist_id", 1], ["created_at", Thu, 11 Aug 2011 18:30:34 UTC +00:00], ["featured", nil], ["song_id", 6], ["updated_at", Thu, 11 Aug 2011 18:30:34 UTC +00:00]]
(0.1ms) COMMIT
注意:["featured", nil]
知道我做错了什么吗?如何在不直接访问的情况下正确设置我的加入属性?
谢谢!
编辑: 为了让我的问题更清楚:
从一个艺术家的例子中,我无法通过
featured_songs关系创建新的精选歌曲保存似乎设置了所有歌曲属性,除了(最重要的)
featuredfeatured属性由于某种原因被设置为nil,这是真正的问题。
【问题讨论】:
-
尝试将
:conditions中的has_many更改为:conditions => { :releases => {:featured => true} } -
谢谢你,但不幸的是它没有工作。结果还是
["featured", nil] -
认为
has_many的概念也适用于此。看看api.rubyonrails.org/classes/ActiveRecord/Associations/…,如果你还没有,也许你会发现一些有用的东西。 -
FWIW,到目前为止,没有一个答案对我有用。 :-\
标签: ruby-on-rails activerecord data-modeling relationship has-many-through