【问题标题】:Rails: Making a third object save info from object 1 and 2 when I create a new object 1Rails:当我创建一个新对象 1 时,让第三个对象保存来自对象 1 和 2 的信息
【发布时间】:2012-12-04 18:13:06
【问题描述】:

我有三个模型,分别是 Product、Category 和 Categorization。

产品型号:

    attr_accessible :title, :description, :price, :image_url
    has_many :categorizations
    has_many :categories, :through => :categorizations

类别模型:

    attr_accessible :name
    has_many :categorizations
    as_many :products, :through => :categorizations

分类模型:

    attr_accessible :category_id, :product_id
    belongs_to :category
    belongs_to :product

在创建产品模型时如何创建分类对象?我已经在新产品表单中添加了类别选择。

基本上,当它创建新产品对象时,我想推入 product_id 和选定的 category_id 并创建一个新的分类对象,以便我可以将产品与类别相关联。

新产品的_form.html:

    <div>
        <%= f.label :title %>:<br />
        <%= f.text_field :title %><br />
      </div>
      <div>
        <%= f.label :description %>:<br />
        <%= f.text_area :description, :rows => 6 %>
      </div>
      <div>
        <%= f.label :price %>:<br />
        <%= f.text_field :price %><br />
      </div>
      <div>
        <%= f.label :image_url %>:<br />
        <%= f.text_field :image_url %><br />
      </div>

      <% @categories.each do |category| %>

      <div>
        <% f.fields_for :categorization do |builder| %>
        <%= render 'categorization_fields', :f => builder, :product => @product,         :category => category %>
      </div>
      <% end %>
      <% end %>

products_controller:

    def index
        @products = Product.all
      end

      def new
        @category = Category.all
        @product = Product.new
        @categories = @category.find(params[:category])
        categorization = @product.categorizations.build
      end

      def create
        @product = Product.new(params[:product])
        if @product.save
          redirect_to products_path
        else
          render :new
        end
      end

      def edit
        @product = Product.find(params[:id])
      end

      def update
        @product = Product.find(params[:id])
        if @product.update_attributes(params[:product])
          redirect_to @product
        else
          render :edit
        end
      end

      def show
        @product = Product.find(params[:id])
      end

      def destroy
        @product = Product.find(params[:id])
        @product.destroy
        redirect_to products_path
      end

    end

我无法让它在产品模型中使用 Accept_nested_attributes_for 像这样工作。

任何帮助将不胜感激。

【问题讨论】:

  • 我是不是走错了路?我经历了 Ryan Bates railscast 基本上说做 has_many :through 是最好的做法。所以我试图弄清楚如何让它以这种方式工作。如果没有,我可以做一个简单的连接表来解决这个问题。

标签: ruby-on-rails ruby forms nested


【解决方案1】:

也许您需要将autosave 选项添加到您想要的关系中,例如:

has_many :categorizations, :autosave => true
accepts_nested_attributes_for :categorizations

这应该会在保存您声明关系的模型时保存autosave'd 关系。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-07
    • 2019-07-26
    • 2018-10-28
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    相关资源
    最近更新 更多