Ruby on Rails Model Relationship

39 views Asked by At

I have an app I'm building with Devise for users and admins and I have an admin dashboard where I am trying to build pages that have posts on them. The Page resource is fairly simple as it only has its id key and a name string attribute in the table. The posts table has the page_id as a foreign key and has title:string and content:text attributes. I set up the associations where the models look like this:

class Page < ApplicationRecord
 has_many :posts
end

class Post < ApplicationRecord
 belongs_to :page
end

and the controller looks like this:

class Admin::PostsController < Admin::AdminController

def create
 @admin_page = Admin::Page.find(params[:page_id])
 @admin_post = @admin_page.posts.build(params[admin_page_post])
if @admin_post.save
 redirect_to admin_path
else render 'new'
end

end

private
# Use callbacks to share common setup or constraints between actions.

def admin_page_post
  params.require(:post).permit(:title, :content, :page_id)
end
# Never trust parameters from the scary internet, only allow the white list through.

end

and the form looks like this

<%= simple_form_for(@admin_post, url: admin_page_posts_path) do |f| %>
 <%= f.label :title %> 
 <%= f.text_field :title %>
<b />
 <%= f.label :content %>
 <%= f.text_area :content %>
 <%= f.submit %>
<% end %>

It creates an object in the posts table withe the foreign key of the :page_id however the title and content attributes are nil. Amd I doing the controller create action wrong, maybe my associations are wrong, or my form isn't right or a combination of the three? I'm new to rails development so any feedback would be useful. Thanks!

0

There are 0 answers