has_many :through 不会保存到数据库

发布于 2024-12-23 10:44:44 字数 2406 浏览 0 评论 0原文

我有一个 Item & 协会通过分类进行分类:

class Item < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations, :source => :category
end


class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :items, :through => :categorizations, :source => :item
  attr_accessible :name
end

class Categorization < ActiveRecord::Base
  belongs_to :item
  belongs_to :category
end

Items/new:

<div class="container">
<%= render 'shared/error_create_item_messages'%>
<br/>

<%= form_for(@item, :html => {:multipart => true} ) do |f| %>

    <div class="clearfix">      
       <label>
         <%= f.label :name %>
      </label>
      <div class="input">       
         <%= f.text_field :name %>
      </div>
    </div>


     <div class="clearfix">
        <label>
         <%= f.label :category %>
        </label>

        <%= hidden_field_tag "product[category_ids][ ]", nil %>     
        <% Category.all.each do |category| %>
          <div class="input">           
               <%= check_box_tag "item[category_ids][ ]", category.id, 
                                            @item.category_ids.include?(category.id) %>
              <%= category.name %>
          </div>    
         <% end %>
     </div>     

     <div class="action">
        <div class="btn_create_item_align">
        <%= f.submit "Create item", :class=>"btn primary" %>
        </div>
     </div>

<% end %>
</div>

Categorizations_controller

class CategorizationsController < ApplicationController
   def create
     @categories = Category.all
     Categorization.create(:item_id => item.id, :category_id => category.id)
     Categorization.save
   end

  def edit
  end

end

Items_controller

def create
    @item = @current_user.items.build(params[:item])
    @categories = Category.all
    if @item.save
      redirect_to @item
    else
      render 'new'
    end
 end

问题是当我点击保存(创建项目)时,我检查分类表并检查控制台上的内容,保存的项目仍然没有category_id。 因此,新商品及其属性(名称、描述、价格)会正确保存到数据库中,但类别不会保存到数据库中。它不会保存到数据库。

有什么想法吗? (Rails 新手) 谢谢

I have an association of Item & Category through Categorization:

class Item < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations, :source => :category
end


class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :items, :through => :categorizations, :source => :item
  attr_accessible :name
end

class Categorization < ActiveRecord::Base
  belongs_to :item
  belongs_to :category
end

Items/new:

<div class="container">
<%= render 'shared/error_create_item_messages'%>
<br/>

<%= form_for(@item, :html => {:multipart => true} ) do |f| %>

    <div class="clearfix">      
       <label>
         <%= f.label :name %>
      </label>
      <div class="input">       
         <%= f.text_field :name %>
      </div>
    </div>


     <div class="clearfix">
        <label>
         <%= f.label :category %>
        </label>

        <%= hidden_field_tag "product[category_ids][ ]", nil %>     
        <% Category.all.each do |category| %>
          <div class="input">           
               <%= check_box_tag "item[category_ids][ ]", category.id, 
                                            @item.category_ids.include?(category.id) %>
              <%= category.name %>
          </div>    
         <% end %>
     </div>     

     <div class="action">
        <div class="btn_create_item_align">
        <%= f.submit "Create item", :class=>"btn primary" %>
        </div>
     </div>

<% end %>
</div>

Categorizations_controller

class CategorizationsController < ApplicationController
   def create
     @categories = Category.all
     Categorization.create(:item_id => item.id, :category_id => category.id)
     Categorization.save
   end

  def edit
  end

end

Items_controller

def create
    @item = @current_user.items.build(params[:item])
    @categories = Category.all
    if @item.save
      redirect_to @item
    else
      render 'new'
    end
 end

The problem is When i hit save (create Item), and i check the Categorization table and check the on console, The items saved still dont have category_id.
So the new item and its attributes (name, description, price) is saved to DB properly, but NOT the category. It wont save to db.

Any ideas? (Newbie in Rails)
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沉鱼一梦 2024-12-30 10:44:44

表单 POST 到 ItemsController#create 和 CategorizationsController#create 未被调用(您可以使用一些 放置调试)。

您可以使用 accepts_nested_attributes_for 让 Item 的创建操作完成所有工作。诀窍是仅创建复选框被选中的类别关联,您可以使用 :reject_if 选项(请参阅 Rails API 文档以获取更多信息):

app/models/item.rb:

class Item < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations, :source => :category
  accepts_nested_attributes_for :categories, 
                                :reject_if => proc{|c| c[:persist].blank?}
end

然后您可以为嵌套对象创建表单字段,一个复选框每个类别。

app/views/items/new.html.erb:

<%= form_for @item do |f| %>
  <%# stuff to generate item fields... %>

  <%= f.fields_for :categories do |cat| %>
    <%= cat.check_box :persist %>
    <%= cat.label :name, cat.name %>
  <%- end %>

  <%# submit button, etc. %>
<%- end %>

通过构建(但不保存)与项目关联的类别来填充创建新项目时可供选择的类别集。这可以有效地将代码从您的视图移动到控制器:

app/controllers/items_controller.rb:

def new  
  @item = Item.new  
  Category.all.each {|cat| @item.categories.build(cat.attributes) }  
end

params 放入该控制器操作中将很有教育意义,因此您可以看到从表单发送的哈希值是什么样的。

The form POSTs to ItemsController#create, and CategorizationsController#create isn't being called (you can verify this with some puts debugging).

You can use accepts_nested_attributes_for to have the Item's create action do all the work. The trick is to only create Category associations whose boxes are checked, and you can do that with the :reject_if option (see Rails API doc for more info):

app/models/item.rb:

class Item < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations, :source => :category
  accepts_nested_attributes_for :categories, 
                                :reject_if => proc{|c| c[:persist].blank?}
end

Then you can create form fields for the nested objects, one checkbox per category.

app/views/items/new.html.erb:

<%= form_for @item do |f| %>
  <%# stuff to generate item fields... %>

  <%= f.fields_for :categories do |cat| %>
    <%= cat.check_box :persist %>
    <%= cat.label :name, cat.name %>
  <%- end %>

  <%# submit button, etc. %>
<%- end %>

Populate the set of Categories to choose from when creating a new Item by building (but not saving) Categories associated with the Item. This is effectively moving code from your view to the controller:

app/controllers/items_controller.rb:

def new  
  @item = Item.new  
  Category.all.each {|cat| @item.categories.build(cat.attributes) }  
end

It'll be educational to puts the params in that controller action, so you can see what the hashes being sent from the form look like.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文