2013-06-05 26 views
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爲零,地址填充數據。怎麼來的!

回答

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