【问题标题】:Cannot save check_box_tag data with has_many through无法通过 has_many 保存 check_box_tag 数据
【发布时间】:2016-04-07 04:00:42
【问题描述】:

我正在尝试将复选框数据保存在项目表中

在项目控制器中

 def new
    @project = Project.new
    @allTags = Tag.all
    @allBenefits = Benefit.all
  end



 def create
    p params[:projectName]; # this always throws nil even there is a value
    @project = Project.new(project_params)
    #@tagging = @project.tagging.create!(:project=>Project.id,:tag=>1)

    if @project.save
      redirect_to :action => 'index'
    else
      render :action => 'new'
    end
  end

  def project_params
     params.require(:com_a_b_c_project).permit(:projectName, :briefDesc, :whatSection, :challengers, :status, :valueProposal, :maturityLevel,:tag_ids =>[])
  end

在项目新视图中

<h4><label for = "tags">Tags</label></h4>

<% @allTags.each do |tag| %>
    <p><%= f.label tag.tagName %></p>
    <%= check_box_tag :tag_ids, tag.id, @project.tags.include?(tag), :name => 'project[tag_ids][]'-%>
 <%end%>



class Com::a::b::c::Project < ActiveRecord::Base
     has_many :taggings 
     has_many :tags, :through => :taggings
     accepts_nested_attributes_for :tags 
    end

class Com::a::b::c::Tag < ActiveRecord::Base
  has_many :taggings 
 has_many :projects, :through => :taggings
end


class Com::a::b::c::Tagging < ActiveRecord::Base
  belongs_to :project
  belongs_to :tag
end

在我的日志中,我得到如下 tag_ids 参数

project"=>{"tag_ids"=>["1", "2"]}

问。我是否必须将数据单独保存到 Tagging 表中,还是因为表中的关联而自动保存数据?

目前标记表上没有保存任何内容。如何存储标记数据?

【问题讨论】:

  • tag_ids 应该保存在哪个表中?关联不存储相关表中的数据,可以使用accepts_nested_attributes_for
  • 我已经在标记表上添加了accept_nested_attributes_for,但仍然没有保存...
  • 通过将@project.taggings.build 添加到带有accepts_nested_attributes_for 的ProjectsController 到模型最终存储带有project_id 的记录。但是 tag_ids 仍然没有被存储在标记表中。

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


【解决方案1】:

如果我遵循正确

class Com::a::b::c::Project < ActiveRecord::Base
 has_many :taggings 
 has_many :tags, :through => :taggings
 accepts_nested_attributes_for :tags 
end

在项目模型上应该允许它被持久化。

【讨论】:

  • 我已将建议添加到 Project ActiveRecord。但仍然没有任何东西持续存在
猜你喜欢
  • 2016-08-24
  • 1970-01-01
  • 2016-01-24
  • 1970-01-01
  • 2017-12-19
  • 1970-01-01
  • 2016-12-04
  • 2013-11-24
  • 2015-12-13
相关资源
最近更新 更多