I'm trying to create a model where every blog post has a number of tags (a separate model) associated to it. In my form, I pass back a separated string of tags along with the post, like "apples,oranges,bananas". I'm eventually going to try and split this string and then create a tag for each string. However, for now I'm just trying to see if I can make one tag with the whole string.
The request is handled by the create method of the posts controller. However, I can't figure out how to create and commit the tag in the posts controller, or at least call the tags controller to delegate the creation. I get the error:
undefined method `new=' for Tag(id: integer, tag_name: string, post_id: integer):Class
This points to the line Tag.new = @post.tags.create(post_params[:tag_name]) of the posts_controller.
Relevant code:
posts_controller
def new
@post = Post.new
end
def create
@post = current_user.posts.create(post_params)
Tag.new = @post.tags.create(post_params[:tag_name])
if @post.save
redirect_to post_path(@post), :notice => "Post was created successfully."
else
render :new
end
end
private
def post_params
params.require(:post).permit(:title, :content_md, :image, :user_id, :year_created, :medium, :dimension_height, :dimension_width, :measurement, :weight_in_pounds, :price, :quantity)
end
tags_controller
class TagsController < ApplicationController
def new
@tag = Tag.new
end
def create
@tag = tag.create(tag_params)
end
private
def tag_params
params.require().permit(:tag_name, :user_id)
end
end
post.rb
class Post < ActiveRecord::Base
# Relations
belongs_to :user
has_many :comments
has_many :post_votes
has_many :tags
accepts_nested_attributes_for :tags
end
tag.rb
class Tag < ActiveRecord::Base
validates :tag_name, presence: true
validates :post_id, presence: true
belongs_to :post
end
Aucun commentaire:
Enregistrer un commentaire