Rails nested model forms: checking for a foreign key if the user does not create a new record

We have a pretty simple application for rails, here is my code:

class Post < ActiveRecord::Base belongs_to :category attr_accessible :category_id, :category_attributes accepts_nested_attributes_for :category, :reject_if => :all_blank end class Category < ActiveRecord::Base has_many :posts end #app/views/posts/_form.html.haml = simple_form_for(@post) do |f| = f.association :category = f.simple_fields_for :category do |cat_f| = cat_f.input :name 

Therefore, when creating a new message, I have the opportunity to select a category (from the selection menu) or create a new one (if it does not exist).

I want to confirm that category_id is present if the user does not want to create a new category

I assume that there is some rail to solve this problem. I know that I can’t just add validates :category_id, :presence => true , as this will crash the form when the user decides to create a new category (and don’t choose one from the drop-down list).

Second question: Recently I read a useful tutorial on rails, which shows how to switch between displaying a category selection menu and fields of a new category so that only one of the two is displayed at any time. Has anyone got a link to something like this?

+4
source share
2 answers

I think I fixed this by replacing:

 validates :category_id, :presence => true 

with

 validates :category, :presence => true 

It seems to have worked. Strange.

PS

I can only imagine that this works because :category is considered present if the user selects something from the drop-down list OR if they create a new category using a nested form with my source code: category_id was only considered as present when the user selected something from the drop-down list and NOT when they created a new record.

+11
source

In your PostsController, you probably want to check the input parameters in your create action to see if category_id is your default value (here -1), and if so, create a new category from the text box. Something like that:

 def create if params[:post][:category_id] != -1 category = Category.create params[:post][:category_name] # make sure category is attached to post end # rest of your create action end 

And something like that in your update action.

As for your second question, this is probably less Rails and better handled by Javascript. It can be pretty easy for you to switch to “use an existing category” or “create a new category”, and then use javascript to replace the DOM objects accordingly.

0
source

Source: https://habr.com/ru/post/1332139/


All Articles