【问题标题】:Editing join table values in rails nested attributes在 Rails 嵌套属性中编辑连接表值
【发布时间】:2013-11-25 02:57:54
【问题描述】:

被这个卡住了一段时间,所以我想我会把它扔掉。

我有两个模型和一个连接模型:

class Container < ActiveRecord::Base
  has_many :theme_containers
  has_many :themes, :through => :theme_containers
end

class Theme < ActiveRecord::Base
  has_many :theme_containers
  has_many :containers, :through => :theme_containers
end

class ThemeContainer < ActiveRecord::Base
  belongs_to :container
  belongs_to :theme
end

盛大。我知道这种关联是有效的,因为在控制台中,当我输入 Theme.first.containers 和 Theme.first.theme_containers 时,我得到了我期望的模型(我暂时手动创建了 theme_container 实例)。

问题在于,在我的主题表单中,我希望能够更新连接数据的属性 (theme_containers)。

这是我的表单的简化版本:

<%= form_for(@theme) do |f| %>
  <%= f.fields_for :theme_containers do |builder| %>
    <%= render 'theme_container_fields', f: builder %>
  <% end %>
<% end %>

当我运行它时,container_fields 部分只呈现一次,并且构建器对象似乎正在查看原始的 @theme 对象。我的方法在这里有什么明显的错误吗?我正在尝试做的事情可能吗?

另外,我正在运行 rails 4,所以我没有使用 accept_nested_attributes_for,并且我设置了强大的参数。我认为这不会影响我的具体问题,但也只是把它扔在那里。

谢谢!

【问题讨论】:

  • 几件事 - 1. 您是否在您的 new 操作中“构建”了 theme_containers 对象? 2. accepts_nested_attributes_for 是否也包含在 theme_containers 模型中?

标签: ruby-on-rails ruby-on-rails-4 nested-attributes has-many-through


【解决方案1】:

我会做以下事情:

class Theme < ActiveRecord::Base
  has_many :theme_containers
  has_many :containers, :through => :theme_containers

  accepts_nested_attributes_for :theme_containers
end

在你的 ThemeController 中:

def new
  @theme = Theme.new
  Container.all.each do |container|
    @theme.theme_container.build(container_id: container.id)
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-12
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多