【问题标题】:Rails 3.2 Nested Form Custom Foreign Key Unable to SaveRails 3.2嵌套表单自定义外键无法保存
【发布时间】:2012-08-10 00:06:42
【问题描述】:

我有这个评论模型:

class Review < ActiveRecord::Base
  attr_accessible :approved, :reviewed_id, :for, :user_id, :text, :rating, :title

  belongs_to :business
  belongs_to :product
end

还有这个产品型号:

class Product < ActiveRecord::Base
  include ApplicationHelper
  belongs_to :business
  belongs_to :catalog
  belongs_to :category

  has_many :reviews, :foreign_key => :reviewed_id
  has_many :features, :dependent => :destroy
end

以及这种商业模式:

class Business < ActiveRecord::Base
  validates_presence_of :name
  validates_presence_of :category

  mount_uploader :photo, PhotoUploader

  has_many :catalogs, :dependent => :destroy
  has_many :products, :dependent => :destroy
  has_many :branches, :dependent => :destroy
  has_many :reviews, :foreign_key => :reviewed_id
end

但是在评论控制器中使用这个创建操作:

def create
  @business = Business.find(params[:business_id])

  if params.has_key?('product_id')
    @product = Product.find(params[:product_id])
    @review = @product.reviews.build(params[:review])

    if @review.save
      flash[:notice] = 'Pending Review Submitted'
      redirect_to business_product_path(@business, @product)
    else
      @form_resources = [@business, @product, @review]
      respond_with(@business, @product, @review)
    end
  else
    @review = @business.reviews.build(params[:review])

    if @review.save
      flash[:notice] = 'Pending Review Submitted'
      redirect_to business_path(@business)
    else
      @form_resources = [@business, @review]
      respond_with(@business, @review)
    end
  end
end

我无法保存关联。 simple_form 说有错误,但我在日志中看不到错误,并且所有其他字段都经过验证,所以我猜测关联存在问题。

附带问题:如何让 simple_form 显示所有错误?

【问题讨论】:

    标签: ruby-on-rails associations ruby-on-rails-3.2 form-processing


    【解决方案1】:

    通过使用多态关联并摆脱评论模型中的 for 和 review_id 来修复它。参考这里:

    http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

    【讨论】:

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