Talk to people,
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 test each only has one: name as parameter, but I can not create a Project with album. Here's 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 does not take either the name of the project or the album, but if you create an album / new it gets the name of the album.
I'm finding it difficult to find something to help with the controller for rails 4 has_one.
Thank you.