0

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

邮政

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

邻里邮政控制器

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 并且地址填充了数据。怎么来的!

4

1 回答 1

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

于 2013-06-05T10:53:47.847 回答