Nested Objects has_one Rails 4

Asked

Viewed 62 times

0

Fala galera,

I’m new to Rails and I’m trying to make a crud with two objects , a Project and another Album. Project has_one Album , as a test each one has only one :name as parameter , but I cannot create a Project with album. Here is my code :

project.Rb , album.Rb

class Project < ActiveRecord::Base
 has_one :album
 accepts_nested_attributes_for :album, allow_destroy: true
end

class Album < ActiveRecord::Base
  belongs_to :project
end

Projectscontroller.Rb

def new
 @project = Project.new
 @album = @project.build_album
end

def create
 @project = Project.new
 @album = @project.create_album(params[:album])

respond_to do |format|
  if @project.save
    format.html { redirect_to @project, notice: 'Project was successfully created.' }
    format.json { render :show, status: :created, location: @project }
  else
    format.html { render :new }
    format.json { render json: @project.errors, status: :unprocessable_entity }
  end
end
end

def project_params
  params.require(:project).permit(:name, album_attributes: [:name])
end

_form.html.erb (project)

<%= form_for(@project) do |f| %>
  <% if @project.errors.any? %>
    <div id="error_explanation">
  <h2><%= pluralize(@project.errors.count, "error") %> prohibited this project from being saved:</h2>
  <ul>
   <% @project.errors.full_messages.each do |message| %>
    <li><%= message %></li>
   <% end %>
  </ul>
    </div>
   <% end %>

   <div class="field">
    <%= f.label :name, 'Project name: ' %><br>
     <%= f.text_field :name %>
   </div>

 <%= f.fields_for :album do |a| %>
   <div class="field">
     <%= a.label :name, 'Album name' %><br />
     <%= a.text_field :name %>
   </div>
 <% end %>

<div class="actions">
<%= f.submit %>
</div>

Routes.Rb

  resources :projects do
   resources :albums
  end

When I create a project/new it is not taking the name of the project or the album, but if I create an album/new it takes the name of the album.

I’m finding it hard to find something to help with the has_one controller of Rails 4.

Thank you.

1 answer

1

The idea of using the accepts_nested_attributes_for is you do not need to create the album explicitly as you are doing in the create method.

Just initialize the project with the parameters received from the form that the album should be created together.

@project = Project.new(project_params)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.