Ror2

Building a Rails app with an Association

Sep 29, 2018 by ohiodn8




In this tutorial, we will be building a rails web app named blaze. The application will be able to create posts and have an association to category. Its a short tutorial that is a starting point to help out with this

http://www.trailblazing.in/blogs/search-in-ruby-on-rails-app-with-ransack


Let's Begin

rails new blaze
rails g scaffold Post title:string body:text
rails g scaffold Category title:string


Association in models

Category.rb => 

has_may :posts, dependent: :destroy

Post.rb =>

belongs_to :category


On terminal:

rails g migration add_category_id_to_posts category_id:integer


Controller Setup

categories_controller.rb => 

 def show
    @posts = @category.posts    
  end


posts_controller.rb =>

def new

@post =Post.new

@category = Category.all

end

private

def post_params
params.require(:post).permit(:title, :category_id, :body)
end



Views

/views/posts/form.html.erb => 

      <div class="field">
      <%= f.label :category %>: </br>
        <%= f.collection_select :category_id, Category.all, :id , :title, :include_blank => "select One" %>
      </div>

/views/posts/index.html.erb => 

 (In @post.each do |posts| . . .)

<p><%= post.category.title %></p>


/views/posts/show.html.erb => 

 <strong>Category:</strong>
  <%= link_to @post.category.title, category_path(:id => @post.category.id) %>


Category Views

/categories/index.html.erb =>

  <% @categories.each do |category| %>

<h4><%= link_to category.title, category %></h4>

<% end %>


/category/show.html.erb => 

<h2><%= @category.title %></h2>
<% if @posts.each do |post| %>
  <h2><%= link_to post.title, post %></h2>
<% end.empty? %>
  <p> Please Check back again to see if we have this posts in this Category. </p>
<% end %>





About ohiodn8

Ruby on Rails developer, AWS Engineer, anything fun, music, a little bit of mobile game. . .

Comments





Blogs to Check Out


NodeJS - Express Setup

by TheBlogger