【问题标题】:Polymorphic nested_form saving in rails多态nested_form保存在rails中
【发布时间】:2013-06-05 09:52:00
【问题描述】:

用户可以创建不同类型的帖子。我设置了一个多态关系。

发帖

class Post < ActiveRecord::Base
  attr_accessible :user_id, :address

  belongs_to :postable, polymorphic: true, dependent: :destroy
  belongs_to :user

  validates_presence_of :user_id, :postable_id, :postable_type
end

社区邮报

class NeighborhoodPost < ActiveRecord::Base
  has_one :user, through: :post
  has_one :post, as: :postable, autosave: true, validate: false

  attr_accessible :content, :title, :post_attributes

  accepts_nested_attributes_for :post
end

NeighborhoodPostsController

def create
  params[:neighborhood_post][:post_attributes][:user_id] = current_user.id

  @neighborhood_post = NeighborhoodPost.new(params[:neighborhood_post])
  if @neighborhood_post.save
    redirect_to root_url, notice: 'NeighborhoodPost was successfully created.'
  else
    render action: "new"
  end
end

社区发帖形式

= f.fields_for :post do |post_builder|
  .control-group
    = post_builder.label :address, 'Adres', class: 'control-label'
    .controls
      = post_builder.text_field :address, placeholder: "Adres voor locatie"

这确实有效。但是,我不喜欢在创建操作中编辑参数。当我尝试执行以下操作时:

@neighborhood_post = current_user.neighborhood_posts.create(params[:neighborhood_post])

...它实际上创建了 两个 帖子。一种设置了 user_id 并且地址为 nil 一种其中 user_id 为 nil 并且地址填充了数据。怎么会!

【问题讨论】:

    标签: ruby-on-rails forms associations polymorphism


    【解决方案1】:

    当你建立你的post 时,我假设你做这样的事情:

    @neighborhood_post = NeighborhoodPost.new
    @neighborhood_post.build_post
    

    你只需要走得更远一点:

    @neighborhood_post.build_post( user_id: current_user.id )
    

    然后在你的表格中:

    = f.fields_for :post do |post_builder|
      = post_builder.hidden_field :user_id
    

    这种方法的缺点是您必须-ahem- 信任用户输入,或者以某种方式验证帖子是否具有有效的 user_id (== current_user.id)。因此,如果您不想信任用户输入,我想另一种方法是执行以下操作:

    class NeigborhoodPost < ActiveRecord::Base
    
      def self.new_from_user( user, params = {}, options = {}, &block )
        new( params, options, &block ).tap do |new_post|
          new_post.post.user_id = user.id if new_post.post.present?
        end
      end
    
    end
    

    然后在您的create 操作中:

    @neighborhood_post = NeighborhoodPost.new_from_user( user, params[:neighboorhood_post] )
    

    另一种选择是反转过程:Postaccepts_nested_attributes_for :postable,您将使用 current_user.posts.new( params[:post] ) 创建帖子。 YMMV

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2014-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多