I'm new to rails and apologize if this is a n00b question.
I'm making the obligatory recipe management site and want to have each recipe have a list of tags (where the tag db just contains a string called "name" ). Here are my models to give you some context:
class Recipe < ActiveRecord::Base
has_many :links
has_many :tags, :th开发者_如何学运维rough => :links
validates :name, :ingredients, :directions, :presence => true
accepts_nested_attributes_for :tags,
:allow_destroy => true,
:reject_if => :reject_tag
def reject_tag(a)
...
end
end
class Tag < ActiveRecord::Base
has_many :links
has_many :recipes, :through => :links
end
class Link < ActiveRecord::Base
belongs_to :recipe
belongs_to :tag
end
Basically each recipe has a list of tags through the link connector table and vice versa. The recipe form is accepting nested attributes for the tags. The behavior I want is for duplicated tags to not be entered into the tags table, but just a new link pointing to the already existing tag be created. So if I have a tag with name "Healthy" and enter a new recipe and add the tag "Healthy" to it I don't want duplicate "Healthy" tags in the tag table. All that's needed is a new entry in the link table linking the new recipe to the old tag.
What's the 'rails' approach to doing this. Right now I'm trying to hack it by passing the recipe_id in a hidden input field into the :reject_if lambda and save a new link there. It works for editing an existing recipe, but not for creating a new one, since there is no recipe.id yet. This feels like a bad approach and I'm just not sure how to go about this. Any help is appreciated.
I think your question is answered here: accepts_nested_attributes_for with find_or_create?
Can you double check your model design? Recipe and Tag seems to be having a HABTM through Link relation instead of has_many from both ways. Once you have that, the duplication problem should be solved/easy to solve.
精彩评论