Ruby on Rails中另一个模型形式的模型表单

时间:2014-06-23 15:56:05

标签: ruby-on-rails ruby forms model associations

我在名为Content的模型中有Playlist模型,PlaylistItem模型和连接关联。

这是他们联系的方式:

class Content < ActiveRecord::Base
  has_many :playlist_items
  has_many :playlists, through: :playlist_items
end

class Playlist < ActiveRecord::Base
  has_many :playlist_items, -> { order 'position ASC' }
  has_many :contents, through: :playlist_items
end

class PlaylistItem < ActiveRecord::Base
  belongs_to :content
  belongs_to :playlist
end

当我修改Playlist时,表单只显示其字段Name,这是它唯一的属性。但我希望能够在该表单中的Content(在某个Playlist中添加position,这是PlaylistItem唯一的属性。

我该怎么做?


这是我现在的代码:

<%= form_for(@playlist) do |f| %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>

  <%= f.fields_for :playlist_items do |builder| %>
        <fieldset>
          <%= builder.label :content, "Content ID" %><br>
          <%= builder.text_area :content_id %>
        </fieldset>
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

1 个答案:

答案 0 :(得分:0)

首先,您可以让Playlist模型接受playlist_items的嵌套属性。

class Playlist < ActiveRecord::Base
  has_many :playlist_items, -> { order 'position ASC' }
  has_many :contents, through: :playlist_items
  accepts_nested_attributes_for :playlist_items
end

然后,您可以添加content_id作为集合选择,这将为每个播放列表项创建内容的下拉选项。

<%= f.fields_for :playlist_items do |builder| %>
  <%= builder.label :position %><br>
  <%= builder.integer :position %><br>
  <%= builder.label :content %><br>
  <%= builder.collection_select :content_id, @contents, :id, :title, include_blank: 'Please Select' %>
<% end %>

最后,在您的控制器中,您需要允许将播放列表项属性作为参数传递,并设置@contents实例变量。

class PlaylistController < ApplicationController
  before_action :load_contents, only: [:new, :edit]

  def edit
    @playlist = Playlist.find(params[:id])
    # Build 10 playlist_items to be added to your playlist
    10.times do; @playlist.playlist_items.build; end
  end

  private
    def load_contents
      @contents = Content.all # or another query to get the specific contents you'd like
    end

    def playlist_params
      params.require(:playlist).permit(:name, playlist_items_attributes: [:id, :position, :content_id])
    end
end

请记住,您需要构建您要使用的每个播放列表项。您可以根据需要在newedit方法中执行此操作。