Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## category.rb (Model)
- class Category
- include DataMapper::Resource
- property :id, Serial
- property :name, String
- has n, :categorizations
- has n, :posts, :through => :categorizations
- end
- ## categorization.rb (Model)
- class Categorization
- include DataMapper::Resource
- property :id, Serial
- property :created_at, DateTime
- belongs_to :category
- belongs_to :post
- end
- ## post.rb (Model)
- class Post
- include DataMapper::Resource
- property :id, Serial
- property :title, String
- property :body, Text
- property :created_at, DateTime
- has n, :categorizations
- has n, :categories, :through => :categorizations
- has n, :comments
- end
- ## posts.rb (select actions)
- def new
- @categories = Category.all
- only_provides :html
- @post = Post.new
- display @post
- end
- def create(post)
- cats = post['categories']
- post.delete('categories')
- @post = Post.new(post)
- if @post.save
- # This is where I am having my problems.
- # I need to be able to save the existing categories to the @post.
- # I have been able to establish that "Category.all(:id => cats)" returns as expected with the correct categories.
- @post.categories = Category.all(:id => cats)
- @post.save
- redirect resource(@post), :message => {:notice => "Post was successfully created"}
- else
- message[:error] = "Post failed to be created"
- render :new
- end
- end
- ## new.html.haml (New Post View)
- %h1 New Post
- = error_messages_for :post
- = form_for(@post, :action => url(:posts) ) do
- %p= text_field :title, :label => "Title"
- %p= text_area :body, :label => "Body"
- %p= select :categories, :collection => @categories.map{|c| [c.id, c.name]}, :multiple => true
- %p= submit "Create"
- = link_to 'Back', url(:posts)
Add Comment
Please, Sign In to add comment