Witam.
Mam problem z walidacją danych podczas dodawania gdy używam nested_forms. Najpierw może klasy modelu
class Topic < ActiveRecord::Base
belongs_to :forum
belongs_to :user
has_many :posts, dependent: :destroy
validates :forum, presence: true
validates :user, presence: true
validates :name, length: { minimum: 4, maximum: 64 }
default_scope -> { order(created_at: :desc) }
accepts_nested_attributes_for :posts
end
class Post < ActiveRecord::Base
belongs_to :topic, :inverse_of => :posts
belongs_to :user
validates :topic, presence: true
validates :user, presence: true
validates :content, length: { minimum: 10 }
default_scope -> { order(created_at: :desc) }
end
A teraz akcja kontrolera
def create
@topic = Topic.new name: params[:topic][:name], forum_id: params[:id], user_id: current_user.id
@topic.posts.new content: params[:topic][:posts_attributes]["0"][:content], user_id: current_user.id
@topic.transaction do
respond_to do |format|
if @topic.save
format.html { redirect_to forum_topics_path(params[:id]), notice: 'Topic was successfully created.' }
else
format.html { render :new }
end
end
end
end
W wyniku takiej sytuacji podczas tworzenia tematu nie jest on tworzony bo obiekt typu Post oczekuje już stworzonego tematu, a ten przecież jest tworzony wraz z nim. Jakieś pomysły jak to rozwiązać.