Guest User

Untitled

a guest
May 26th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. ## category.rb (Model)
  2. class Category
  3. include DataMapper::Resource
  4.  
  5. property :id, Serial
  6. property :name, String
  7.  
  8. has n, :categorizations
  9. has n, :posts, :through => :categorizations
  10.  
  11. end
  12.  
  13. ## categorization.rb (Model)
  14. class Categorization
  15. include DataMapper::Resource
  16.  
  17. property :id, Serial
  18. property :created_at, DateTime
  19.  
  20. belongs_to :category
  21. belongs_to :post
  22.  
  23. end
  24.  
  25. ## post.rb (Model)
  26. class Post
  27. include DataMapper::Resource
  28.  
  29. property :id, Serial
  30. property :title, String
  31. property :body, Text
  32. property :created_at, DateTime
  33.  
  34. has n, :categorizations
  35. has n, :categories, :through => :categorizations
  36.  
  37. has n, :comments
  38.  
  39. end
  40.  
  41. ## posts.rb (select actions)
  42. def new
  43. @categories = Category.all
  44. only_provides :html
  45. @post = Post.new
  46. display @post
  47. end
  48.  
  49. def create(post)
  50. cats = post['categories']
  51. post.delete('categories')
  52. @post = Post.new(post)
  53. if @post.save
  54. # This is where I am having my problems.
  55. # I need to be able to save the existing categories to the @post.
  56. # I have been able to establish that "Category.all(:id => cats)" returns as expected with the correct categories.
  57. @post.categories = Category.all(:id => cats)
  58. @post.save
  59. redirect resource(@post), :message => {:notice => "Post was successfully created"}
  60. else
  61. message[:error] = "Post failed to be created"
  62. render :new
  63. end
  64. end
  65.  
  66. ## new.html.haml (New Post View)
  67. %h1 New Post
  68.  
  69. = error_messages_for :post
  70.  
  71. = form_for(@post, :action => url(:posts) ) do
  72. %p= text_field :title, :label => "Title"
  73. %p= text_area :body, :label => "Body"
  74. %p= select :categories, :collection => @categories.map{|c| [c.id, c.name]}, :multiple => true
  75.  
  76. %p= submit "Create"
  77.  
  78. = link_to 'Back', url(:posts)
Add Comment
Please, Sign In to add comment