I'm new on rails , im trying to do a crud with 2 objects and has_one relation, i have a Project and Album , and just a :name property for each one. But when i create a project, both names are blank. 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 the project/new don't work, but if i create album/new the album get a name.
Thanks!
Aucun commentaire:
Enregistrer un commentaire