我在令牌输入上关注了 Ryan Bate 的 Railscast,它在我的“发布”级别上完美运行,使用:
<%= f.text_field :artist_tokens, "data-pre" => @release.artists.map(&:attributes).to_json, :class => "text" %
在发行版中,我有“曲目”,并希望能够在曲目级别修改和更改艺术家。使用上面的方法,我可以让它“继承”发布级别的艺术家,这对于新方法和初始设置来说似乎工作正常,但是在编辑时它显然会拉回发布级别的艺术家,如果提交它命中,那么所有轨道水平艺术家被覆盖。
我正在尝试这样做:
<% if params[:action] == "edit" %>
<%= f.text_field :artist_tokens, "data-pre" => @track.artists.map(&:attributes).to_json, :class => "text" %>
<% else %>
<%= f.text_field :artist_tokens, "data-pre" => @release.artists.map(&:attributes).to_json, :class => "track_artist_tokens" %>
<% end %>
但是我在@track.artists.map 上得到了一个未定义的方法“艺术家”
我的模型如下:
class Release < ActiveRecord::Base
has_many :artist_releases
has_many :artists, :through => :artist_releases
attr_reader :artist_tokens
def artist_tokens=(ids)
self.artist_ids = ids.split(",")
end
has_many :releases_tracks, :dependent => :destroy
has_many :tracks, :through => :releases_tracks
accepts_nested_attributes_for :tracks, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => :true
has_many :artists_tracks
end
class Artist < ActiveRecord::Base
has_many :artist_releases
has_many :releases, :through => :artist_releases
has_many :artists_tracks
has_many :tracks, :through => :artists_tracks
end
class Track < ActiveRecord::Base
has_many :releases_tracks, :dependent => :destroy
has_many :releases, :through => :releases_tracks
has_many :artists_tracks
has_many :artists, :through => :artists_tracks
attr_reader :artist_tokens
def artist_tokens=(ids)
self.artist_ids = ids.split(",")
end
end
class ArtistsTrack < ActiveRecord::Base
belongs_to :artist
belongs_to :release
belongs_to :track
end
class ReleasesTrack < ActiveRecord::Base
belongs_to :release
belongs_to :track
acts_as_list
end
任何人都可以帮忙吗?
更新:
释放控制器轨道方法:
def tracks
@release = Release.find(params[:id])
@track = @release.tracks.find(:all)
respond_to do |format|
format.html # tracks.html.erb
end
end
track.html.erb 有:
<%= form_for @release do |f| %>
<%= f.fields_for :tracks do |builder| %>
<%= render 'track_fields', :f => builder %>
<% end %>
<% end %>
_track_fields.html.erb 部分(为了清楚起见,去掉了一些 HTML)
<td class="label">Title:</td>
<td class="field"><%= f.text_field :name, :class => "text" %></td>
<td class="label">Artists:</td>
<td class="field">
<% @track.each do |track| %>
<%= f.text_field :artist_tokens, "data-pre" => track.artists.map(&:attributes).to_json, :class => "track_artist_tokens" %>
<% end %>
<p><%= link_to 'Add new artist', new_artist_path, :remote => true %></p>
<td class="label">Version:</td>
<td class="field"><%= f.text_field :version, :class => "text" %></td>
<td class="label">ISRC:</td>
<td class="field"><%= f.text_field :isrc, :class => "text" %></td>
<td class="label">Remove:</td>
<td class="field"><%= f.check_box :_destroy %></td>