0
用戶可以創建不同類型的帖子。我設置了一個多態關係。導軌中的多態nested_form保存
後
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
NeighborhoodPost
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爲零,地址填充數據。怎麼來的!