I want to loop through attributes which are validated with custom validation method. I have model Post
which has_many :languages
and a model Language
which belongs_to :post
. In the languages
table I have columns - id, post_id, language
.
Post model:
class Post < ApplicationRecord
has_many :languages
accepts_nested_attributes_for :languages, reject_if: :all_blank
validates_associated :languages
end
Language model:
class Language < ApplicationRecord
validate :unique_languages?
def unique_languages?
#LOOP ATTRIBUTES
end
end
IIn the Language
model in the unique_languages?
I want too loop through all language attributes of the post. This is posts_controller
with strong params and logic for creating a post:
class PostsController < ApplicationController
def new
@post = Post.new
@post.languages.build if @post.languages.empty?
end
def create
@post = Post.new(post_params)
@post.languages.build if @post.languages.empty?
if @post.save
redirect_to action: 'new'
else
render 'new'
end
end
private
def post_params
params.require(:post).permit(:title, languages_attributes: [:language])
end
end
Aucun commentaire:
Enregistrer un commentaire