用户可以创建不同类型的帖子。我设置了一个多态关系。
邮政
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 并且地址填充了数据。怎么来的!