I have problem and I can't figure out how to solve this, I tried trace every character on codes but I think I didn't get mistake on code
I have 3 models : Product, AttributeProduct and AttributeProductRelation, and relations :
class Product < ActiveRecord::Base
has_many :attribute_product_relations
has_many :attribute_products, through: :attribute_product_relations
accepts_nested_attributes_for :attribute_product_relations, allow_destroy: true
end
class AttributeProduct < ActiveRecord::Base
has_many :attribute_product_relations
has_many :products, through: :attribute_product_relations
end
class AttributeProductRelation < ActiveRecord::Base
belongs_to :product
belongs_to :attribute_product
end
And on ProductsController I have this :
def new
#product = Product.new(id: generate_product_id)
2.times { #product.attribute_product_relations.build }
end
def create
#store = current_user.store
#product = #store.products.build(new_product_params)
respond_to do |format|
if #product.save
format.html { redirect_to red_path, notice: I18n.t('notice.create_product_success') }
format.json { render :show, status: :created, location: #product }
else
format.html { render :new }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
private
def new_product_params
params.require(:product).permit(:id, :name :description, attribute_product_relations_attributes: [:id, :product_id, :attribute_product_id, :value])
end
And this is a form :
<%= nested_form_for #product, html: { class: "form-horizontal" } do |f| %>
<%#= order stuff here %>
<%= f.fields_for :attribute_product_relations do |attribute_product_relation_form| %>
<div class="row">
<div class="col-xs-6 col-md-6">
<%= attribute_product_relation_form.hidden_field :attribute_product_id, value: 1 %>
<label class="control-label">size</label>
</div>
<div class="col-xs-6 col-md-6">
<%= attribute_product_relation_form.text_field :value, {class: "form-control text select_short" %>
</div>
</div>
<% end %>
<% end %>
And this is a log when I submit a form :
Started POST "/products" for 127.0.0.1 at 2015-10-09 16:11:51 +0700
Processing by ProductsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"WzSKpXm4AFhETrPyv0Ez/WohxoAMMiiRRc6CNhgIPC8=", "product"=>{"id"=>"2132051", "name"=>"T-shirt", "attribute_product_relations_attributes"=>{"0"=>{"attribute_product_id"=>"1", "value"=>"Medium"}, "1"=>{"attribute_product_id"=>"1", "value"=>"SMALL"}} , "description"=>"cool t-shirt"}, "button"=>""}
You can see attribute_product_relations_attributes are exists on parameter, So I'm use pry-debugger gems to trace new_product_params method and I just get this :
[1] pry(#<ProductsController>)> new_product_params
=> {"id"=>"2132051",
"name"=>"T-shirt"
"description"=>"cool t-shirt"}
I can't see attribute_product_relations_attributes on new_product_params and didn't save to database.
As you are have has many relationship in new_product_params methods, it is required to make permit for array of attribute_product_relations_attributes. So, your should refactor new_product_params method to
def new_product_params
params.require(:product).permit(:id, :name :description, attribute_product_relations_attributes: [ [:id, :product_id, :attribute_product_id, :value] ])
end
I think this will help.
Related
I am trying simple_form nested attributes as suggested in https://github.com/plataformatec/simple_form/wiki/Nested-Models
The thing is, when I render the form I just can see the submit button, but not the input field. What am I doing wrong?
_form.html.erb
<%= simple_form_for [:admin, #incident] do |f| %>
<%= f.error_notification %>
<%= f.simple_fields_for :comments do |builder| %>
<%= builder.input :info, label: "Informe de seguimiento" %>
<% end %>
<div class="form-actions">
<%= f.submit "Enviar", class: "btn btn-primary" %>
</div>
<% end %>
incidents_controller.rb
class Admin::IncidentsController < ApplicationController
before_action :set_incident, only: [:show, :edit, :update]
def index
#incidents = Incident.all
end
def show
end
def new
#incident = Incident.new
#incident.comments.build
end
def edit
end
def update
respond_to do |format|
if #incident.update(incident_params)
format.html { redirect_to #incident, notice: 'Incidencia actualizada actualizada con éxito.' }
format.json { render :show, status: :ok, location: #incident }
else
format.html { render :edit }
format.json { render json: #incident.errors, status: :unprocessable_entity }
end
end
end
private
def set_incident
#incident = Incident.find(params[:id])
end
def incident_params
params.require(:incident).permit(:info, :subject, :status, comments_attributes: [:info])
end
end
incident.rb
class Incident < ApplicationRecord
belongs_to :user, optional: true
has_many :comments, dependent: :destroy
accepts_nested_attributes_for :comments, allow_destroy: true, reject_if: proc { |attributes| attributes['info'].blank? }
enum status: [:abierto, :tramite, :pendiente, :cerrado]
after_initialize :set_default_status, :if => :new_record?
def set_default_status
self.status ||= :abierto
end
end
comment.rb
class Comment < ApplicationRecord
belongs_to :user, optional: true
belongs_to :incident
end
You need to add #incident.comments.build to the show action of Admin::IncidentsController. Now it has no comments, I suppose, so the form is empty.
And you need to add :id to comments_attributes, without it comment can't be saved. If you planning to have some 'Delete' checkbox for existing comments you also need to add :_destroy to the attributes array
I am having issues understanding this.
What am I trying to accomplish?
Selected items in dropdown submitted to inventory.
Change the status of each item in a form in its own model.
Problem
I submit a form and the status of each item in the dropdown doesn't get submitted.
Any help would be appreciated.
Thanks in advance!
Form Code
<%= form_for(#inventory, html: {class: "form-horizontal"}) do |f| %>
<% if #inventory.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#inventory.errors.count, "error") %> prohibited this inventory from being saved:</h2>
<ul>
<% #inventory.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= f.label :tablet_id, "Tablet #", class: "col-md-2 control-label" %>
<div class="col-md-4">
<%= select("inventory", "tablet_id", Tablet.where("status = '1'").all.collect{ |t| [t.alias, t.id] }, {}, { class: "form-control"} ) %>
</div>
</div>
<%= f.fields_for :tablet do |t| %>
<%= t.hidden_field :status, value: 2 %>
<% end %>
<div class="form-group">
<%= f.label :chauffeur_id, "Chauffeur #", class: "col-md-2 control-label" %>
<div class="col-md-4">
<%= select("inventory", "chauffeur_id", Chauffeur.where("status = '1'").all.collect{ |t| [t.chaufNum, t.id] }, {}, { class: "form-control"} ) %>
</div>
</div>
<%= f.fields_for :chauffeur do |t| %>
<%= t.hidden_field :status, value: 2 %>
<% end %>
<div class="form-group">
<%= f.label :vehicle_id, "Vehicle #", class: "col-md-2 control-label" %>
<div class="col-md-4">
<%= select("inventory", "vehicle_id", Vehicle.where("status = '1'").all.collect{ |t| [t.vehNum, t.id] }, {}, { class: "form-control"} ) %>
</div>
</div>
<%= f.fields_for :vehicle do |t| %>
<%= t.hidden_field :status, value: 2 %>
<% end %>
<div class="form-group">
<div class="col-md-2 col-md-offset-2">
<%= f.submit class: "btn btn-sm btn-success" %>
</div>
</div>
<% end %>
Model (Inventory)
class Inventory < ActiveRecord::Base
belongs_to :tablet
belongs_to :chauffeur
belongs_to :vehicle
accepts_nested_attributes_for :tablet
accepts_nested_attributes_for :chauffeur
accepts_nested_attributes_for :vehicle
has_paper_trail
validates :tablet_id, :chauffeur_id, :vehicle_id, presence: true
validates :tablet_id, :chauffeur_id, :vehicle_id, uniqueness: { message: " is already checked out." }
end
Inventory Controller
class InventoriesController < ApplicationController
before_action :authenticate_user!
before_filter :set_paper_trail_whodunnit
before_action :set_inventory, only: [:show, :edit, :update, :destroy]
# GET /inventories
# GET /inventories.json
def index
#inventories = Inventory.all.paginate(:page => params[:page], :per_page => 15)
end
# GET /inventories/1
# GET /inventories/1.json
def show
#versions = PaperTrail::Version.order('created_at DESC')
end
# GET /inventories/new
def new
#inventory = Inventory.new
end
# GET /inventories/1/edit
def edit
end
def history
#versions = PaperTrail::Version.order('created_at DESC')
end
# POST /inventories
# POST /inventories.json
def create
# #inventory = Inventory.new(inventory_params)
render plain: params[:inventory].inspect
# respond_to do |format|
# if #inventory.save
# format.html { redirect_to #inventory, notice: 'Inventory was successfully created.' }
# format.json { render :show, status: :created, location: #inventory }
# else
# format.html { render :new }
# format.json { render json: #inventory.errors, status: :unprocessable_entity }
# end
# end
end
# PATCH/PUT /inventories/1
# PATCH/PUT /inventories/1.json
def update
respond_to do |format|
if #inventory.update(inventory_params)
format.html { redirect_to #inventory, notice: 'Inventory was successfully updated.' }
format.json { render :show, status: :ok, location: #inventory }
else
format.html { render :edit }
format.json { render json: #inventory.errors, status: :unprocessable_entity }
end
end
end
# DELETE /inventories/1
# DELETE /inventories/1.json
def destroy
#inventory.destroy
respond_to do |format|
format.html { redirect_to inventories_url, notice: 'Inventory was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_inventory
#inventory = Inventory.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def inventory_params
params.require(:inventory).permit(:tablet_id, :chauffeur_id, :vehicle_id, tablet_attributes: [:status => '2'], chauffeur_attributes: [:status => '2'], vehicle_attributes: [:status => '2'])
end
end
Clean all your nested attribute code. This is not what you want. So model like this:
class Inventory < ActiveRecord::Base
belongs_to :tablet
belongs_to :chauffeur
belongs_to :vehicle
has_paper_trail
validates :tablet_id, :chauffeur_id, :vehicle_id, presence: true
validates :tablet_id, :chauffeur_id, :vehicle_id, uniqueness: { message: " is already checked out." }
end
Now, what you want to use a rails callback so that when you create an inventory then you update the status of other things. This goes on your model too:
class Inventory < ActiveRecord::Base
...
after_create :update_status
protected
def update_status
self.tablet.update_attribute(:status, 2)
self.chauffeur.update_attribute(:status, 2)
self.vehicle.update_attribute(:status, 2)
end
end
Also remember to clean all your fields_for code and your strong parameters on your controller...you don't need the nested ones anymore.
I have a problem with a form with nested resource. The data model is easy:
class Event < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
has_many :event_contents
end
class EventContent < ActiveRecord::Base
belongs_to :event
end
My form:
= simple_form_for([:admin, #event, #event.event_contents.new], remote: true) do |f|
.chat-form
.input-cont
= f.input :content, label: false, input_html: { class: 'form-control' }
.btn-cont
%span.arrow
= f.submit 'invia', class: 'btn blue icn-only'
The controller:
class Admin::EventContentsController < AdminController
def create
#event_content = EventContent.new event_content_params
#event_content.user_id = current_user.id if current_user
if #event_content.save
respond_to do |format|
format.js { render :nothing => true }
end
else
end
end
private
def event_content_params
params.require(:event_content).permit(
:content,
:event_id,
:user_id
)
end
end
When i submit the post in the params instead of event_id I have the event "slug"
pry(#<Admin::EventContentsController>)> params
=> {"utf8"=>"✓", "event_content"=>{"content"=>"uhm"}, "commit"=>"invia", "action"=>"create", "controller"=>"admin/event_contents", "event_id"=>"test-test-test"}
The record is created in the db, but event_id is nil so the association is broken.
Why instead of the event_id I have the event slug???
Update
The issue was the controller:
def create
#event = Event.find params[:event_id]
#event_content = #event.event_contents.build event_content_params
#event_content.user_id = current_user.id if current_user
if #event_content.save
respond_to do |format|
format.js
end
else
end
end
Maybe try doing the following:
in your Event model add accepts_nested_attributes_for :event_contents
in your form, when you are collecting the :event_contents replace
f.input :content, label: false, input_html: { class: 'form-control' }
with the following:
f.fields_for :event_contents do |content|
content.input :content
end
update your strong params in your Events controller to include {:event_contents_attributes} which might look something like below depending on the other params you need to pass through:
params.require(:event).permit(:name, {:event_contents_attributes => [:content]})
In your Events controller, update def new to include this line item event_content = #event.event_contents.build
All that to say, I believe you would want this to be routed to your Events controller and not your EventContents controller because the :event_contents are nested in the :event. It looks like your form is submitting to the EventContents controller currently. Also, I don't believe this argument in your simple_form_for #event.event_contents.new is necessary.
Here's what I built off of your question. It's not admin namespaced but might be helpful.
class EventsController < ApplicationController
def new
#event = Event.new
event_content = #event.event_contents.build
end
def create
#event = Event.new(event_params)
respond_to do |format|
if #event.save
format.html { redirect_to #event, notice: 'Event was successfully created.' }
format.json { render :show, status: :created, location: #event }
format.js
else
format.html { render :new }
format.json { render json: #event.errors, status: :unprocessable_entity }
end
end
private
def event_params
params.require(:event).permit(:name, {:event_contents_attributes => [:content]})
end
end
Event model:
class Event < ActiveRecord::Base
has_many :event_contents
accepts_nested_attributes_for :event_contents
end
And finally the form:
<%= form_for(#event) do |event| %>
<div class="field">
<%= event.label :name %><br>
<%= event.text_field :name %>
</div>
<%= event.fields_for :event_contents do |content| %>
<div class="field">
<%= content.label :content %>
<%= content.text_field :content %>
</div>
<% end %>
<div class="actions">
<%= event.submit %>
</div>
<% end %>
I have trying to create a nested form with three models associated with through in one.
This is the schema:
These are the models:
../app/models/alimento.rb:
class Alimento < ActiveRecord::Base
attr_accessible :calorias, :nome, :refeicaos_attributes
validates :nome, :calorias, :presence => { :message => "nao pode ficar em branco" }
has_many :controles, :dependent => :destroy
has_many :refeicaos, through: :controles
has_many :diarios, through: :controles
accepts_nested_attributes_for :controles
end
../app/models/refeicao.rb:
class Refeicao < ActiveRecord::Base
attr_accessible :nome, :alimentos_attributes, :controles_attributes, :diario_attributes
validates :nome, :presence => { :message => "nao pode ficar em branco" }
has_many :controles, dependent: :destroy
has_many :alimentos, through: :controles
has_many :diarios, through: :controles
accepts_nested_attributes_for :controles
end
../app/models/diario.rb:
class Diario < ActiveRecord::Base
has_many :controles, dependent: :destroy
has_many :refeicaos, through: :controles
has_many :alimentos, through: :controles
accepts_nested_attributes_for :controles
attr_accessible :data, :controles_attributes, :refeicaos_attributes, :alimentos_attributes
end
../app/models/controle.rb:
class Controle < ActiveRecord::Base
belongs_to :alimento
belongs_to :refeicao
belongs_to :diario
attr_accessible :quantidade, :alimento_id, :refeicao_id, :diario_id
accepts_nested_attributes_for :alimento
accepts_nested_attributes_for :refeicao
accepts_nested_attributes_for :diario
end
I created many alimentos (food) and refeições (meals), now I need create a
daily control of diet through the model Diario that can contain many alimentos and refeições through the Controle (control) model.
../app/controllers/diarios_controller.rb:
class DiariosController < ApplicationController
# GET /diarios
# GET /diarios.json
def index
#diarios = Diario.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #diarios }
end
end
# GET /diarios/1
# GET /diarios/1.json
def show
#diario = Diario.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #diario }
end
end
# GET /diarios/new
# GET /diarios/new.json
def new
#diario = Diario.new
end
# GET /diarios/1/edit
def edit
#diario = Diario.find(params[:id])
end
# POST /diarios
# POST /diarios.json
def create
#diario = Diario.new(params[:diario])
respond_to do |format|
if #diario.save
format.html { redirect_to #diario, notice: 'Diario was successfully created.' }
format.json { render json: #diario, status: :created, location: #diario }
else
format.html { render action: "new" }
format.json { render json: #diario.errors, status: :unprocessable_entity }
end
end
end
# PUT /diarios/1
# PUT /diarios/1.json
def update
#diario = Diario.find(params[:id])
respond_to do |format|
if #diario.update_attributes(params[:diario])
format.html { redirect_to #diario, notice: 'Diario was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #diario.errors, status: :unprocessable_entity }
end
end
end
# DELETE /diarios/1
# DELETE /diarios/1.json
def destroy
#diario = Diario.find(params[:id])
#diario.destroy
respond_to do |format|
format.html { redirect_to diarios_url }
format.json { head :no_content }
end
end
end
I'm trying to do the "Nested Model Form (revised)" example.
Views:
../app/views/diarios/new.html.erb:
<%= form_for #diario do |f| %>
<div class="field">
<%= f.label :data %>
<%= f.date_select :data %>
<br>
</div>
<%= f.fields_for :refeicaos do |builder| %>
<%= render 'refeicao_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Adicionar Refeição", f, :refeicaos %>
</br>
</br>
<div class="actions">
<%= f.submit "Cadastrar Controle" %>
</div>
<% end %>
</br>
<%= link_to 'Voltar', root_path %>
../app/views/diarios/_refeicao_fields.html.erb:
<fieldset>
<strong>Refeição: </strong></br>
<%= f.label :nome, "Nome da Refeição", :style => 'margin-left: 5px;' %>
<%= collection_select(:refeicao, :id, Refeicao.order(:nome), :id, :nome) %>
<%= f.check_box :_destroy %>
<%= f.label :_destroy, "Remover Refeição" %>
</br>
</br>
<strong>Alimentos:</strong></br>
<%= f.fields_for :alimentos do |builder| %>
<%= render 'alimento_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Adicionar Refeição", f, :alimentos %>
</fieldset>
../app/views/diarios/_alimento_fields.html.erb:
<fieldset>
<%= f.label :alimento, "Nome do Alimento:" %>
<%= collection_select(:alimento, :id, Alimento.order(:nome), :id, :nome) %>
<%= f.hidden_field :_destroy %>
<%= f.fields_for :controles do |builder| %>
<%= render 'controle_fields', f: builder %>
<% end %>
<%= link_to "Remover alimento", '#', class: "remove_fields" %></br>
</fieldset>
../app/views/diarios/_controle_fields.html.erb:
<fieldset>
<%= f.label :alimento, "Quantidade:", :style => 'margin-left: 42px;' %>
<%= f.number_field :quantidade, :style => 'width: 50px;' %>
</fieldset>
Custom helper created:
module ApplicationHelper
def link_to_add_fields(name, f, association)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize + "_fields", f: builder)
end
link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end
end
I get this error:
NoMethodError in Diarios#new
Showing D:/aplicacoes_indie/AppDieta/app/views/diarios/_refeicao_fields.html.erb where line #13 raised:
undefined method `alimentos' for nil:NilClass
Extracted source (around line #13):
10: <%= f.fields_for :alimentos do |builder| %>
11: <%= render 'alimento_fields', f: builder %>
12: <% end %>
13: <%= link_to_add_fields "Adicionar Refeição", f, :alimentos %>
14: </fieldset>
I've trying a lot of ways, but I can't solve this. The idea is: A Diario > with 1 or more refeicoes > with 1 or more alimentos and save each association through controle model.
Where am I wrong?
EDITED*
thanks for the answer, now the form appears
But should appear the number field 'quantidade' from controle below the select from alimento like this:
http://uploaddeimagens.com.br/images/000/123/917/full/model2.jpg?1385480010
../app/view/diarios/_alimento_fields.html.erb
<fieldset>
<%= f.label :alimento, "Nome do Alimento:" %>
<%= collection_select(:alimento, :id, Alimento.order(:nome), :id, :nome) %>
<%= f.hidden_field :_destroy %>
<%= f.fields_for :controles do |builder| %>
<%= render 'controle_fields', f: builder %>
<% end %>
<%= link_to "Remover alimento", '#', class: "remove_fields" %></br>
</fieldset>
../app/view/diarios/_controle_fields.html.erb
<fieldset>
<%= f.label :controle, "Quantidade:", :style => 'margin-left: 42px;' %>
<%= f.number_field :quantidade, :style => 'width: 50px;' %>
</fieldset>
One more thing, how can i mount the create action of Diario to get all the values of selects of alimentos and refeicaos and save each in controle model? Because I save and only create a Diario object with none association.
../app/controllers/diarios_controller.rb action create
def create
#diario = Diario.new(params[:diario])
respond_to do |format|
if #diario.save
format.html { redirect_to #diario, notice: 'Diario was successfully created.' }
format.json { render json: #diario, status: :created, location: #diario }
else
format.html { render action: "new" }
format.json { render json: #diario.errors, status: :unprocessable_entity }
end
end
end
I think these are the only accepts_nested_attributes_for statements that you should need:
class Diario < ActiveRecord::Base
accepts_nested_attributes_for :refeicaos
And:
class Refeicao < ActiveRecord::Base
accepts_nested_attributes_for :alimentos
Right now the <%= f.fields_for :refeicaos do |builder| %> statement is setting up the builder but builder.object is nil.
Edit - Changed field names to plural forms since this was a has_many relationship.
try:
class Alimento < ActiveRecord::Base
attr_accessible :calorias, :nome, :refeicaos_attributes
validates :nome, :calorias, :presence => { :message => "nao pode ficar em branco" }
has_many :controles, :dependent => :destroy
has_many :refeicaos, through: :controles
has_many :diarios, through: :controles
accepts_nested_attributes_for :controles
end
class Refeicao < ActiveRecord::Base
attr_accessible :nome, :alimentos_attributes, :controles_attributes, :diario_attributes
validates :nome, :presence => { :message => "nao pode ficar em branco" }
has_many :controles, dependent: :destroy
has_many :alimentos, through: :controles
has_many :diarios, through: :controles
accepts_nested_attributes_for :alimentos
end
class Diario < ActiveRecord::Base
has_many :controles, dependent: :destroy
has_many :refeicaos, through: :controles
has_many :alimentos, through: :controles
accepts_nested_attributes_for :refaicoas
attr_accessible :data, :controles_attributes, :refeicaos_attributes, :alimentos_attributes
end
class Controle < ActiveRecord::Base
belongs_to :alimento
belongs_to :refeicao
belongs_to :diario
attr_accessible :quantidade, :alimento_id, :refeicao_id, :diario_id
end
I get the following error:
ActiveRecord::AssociationTypeMismatch in ContractsController#create
ExchangeRate(#2183081860) expected, got HashWithIndifferentAccess(#2159586480)
Params:
{"commit"=>"Create",
"authenticity_token"=>"g2/Vm2pTcDGk6uRas+aTgpiQiGDY8lsc3UoL8iE+7+E=",
"contract"=>{"side"=>"BUY",
"currency_id"=>"488525179",
"amount"=>"1000",
"user_id"=>"633107804",
"exchange_rate"=>{"rate"=>"1.7"}}}
My relevant model is :
class Contract < ActiveRecord::Base
belongs_to :currency
belongs_to :user
has_one :exchange_rate
has_many :trades
accepts_nested_attributes_for :exchange_rate
end
class ExchangeRate < ActiveRecord::Base
belongs_to :denccy, :class_name=>"Currency"
belongs_to :numccy, :class_name=>"Currency"
belongs_to :contract
end
My view is:
<% form_for #contract do |contractForm| %>
Username: <%= contractForm.collection_select(:user_id, User.all, :id, :username) %> <br>
B/S: <%= contractForm.select(:side,options_for_select([['BUY', 'BUY'], ['SELL', 'SELL']], 'BUY')) %> <br>
Currency: <%= contractForm.collection_select(:currency_id, Currency.all, :id, :ccy) %> <br> <br>
Amount: <%= contractForm.text_field :amount %> <br>
<% contractForm.fields_for #contract.exchange_rate do |rateForm|%>
Rate: <%= rateForm.text_field :rate %> <br>
<% end %>
<%= submit_tag :Create %>
<% end %>
My View Controller:
class ContractsController < ApplicationController
def new
#contract = Contract.new
#contract.build_exchange_rate
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #contract }
end
end
def create
#contract = Contract.new(params[:contract])
respond_to do |format|
if #contract.save
flash[:notice] = 'Contract was successfully created.'
format.html { redirect_to(#contract) }
format.xml { render :xml => #contract, :status => :created, :location => #contract }
else
format.html { render :action => "new" }
format.xml { render :xml => #contract.errors, :status => :unprocessable_entity }
end
end
end
I'm not sure why it's not recognizing the exchange rate attributes?
Thank you
The problem is that accepts_nested_attributes_for :exchange_rate looks for "exchange_rate_attributes" in the params, not "exchange_rate". The fields_for helper will do this for you, but you have to change it to:
<% contractForm.fields_for :exchange_rate do |rateForm|%>