user1611830
user1611830

Reputation: 4867

nested models best practice - rails

Suppose I have two models model1 and model2, and that model2 belongs_to model1 (conversely, model1 has many model2). Suppose now I want to create a model2, from the model1/1 page view, (the page showing the model1 with id 1). Here's what I did :

<%= form_for(@model2, remote: true) do |f| %>
      <%= f.text_field :title %>
      <%= f.submit "POST" %>
<% end %>

(@model2 was instantiated in the model1 controller show method). Is this a best practice ? Should I use nested attributes ?

Upvotes: 0

Views: 356

Answers (2)

Dani&#235;l Zwijnenburg
Dani&#235;l Zwijnenburg

Reputation: 2560

What CDub said is right. However you can achieve the nested CRUD resources this way:

user = model1 post = model2

class user < ActiveRecord::Base
  has_many :posts
end

class post < ActiveRecord::Base
  belongs_to :user
end

In your routes you can do this:

routes.rb

resources :users do
  resources :posts
end

and in your posts controller you can do this:

class UsersController < ApplicationController
  def new
    @post = current_user.posts.new
  end

  def create
    @post = current_user.posts.new(params[:post])
    if @post.save
      redirect_to user_posts_path(current_user, @post)
    else
      render :new
    end
  end
end

You can trigger this route by doing:

<%= link_to 'new post', new_user_post_path(current_user) %>

and edit:

<%= link_to 'edit post', edit_user_post_path(current_user, @post) %>

checkout: nested resources rails api

Upvotes: 1

CDub
CDub

Reputation: 13354

I don't know about the best practices, but I think it makes the most sense to try and only CRUD models within their resource scope. That said, I prefer to use accepts_nested_attributes_for and creating it through a form submission to @model1, but again, it's simply preference - either will work.

Upvotes: 1

Related Questions