I'm trying to create a record in a join table named Interventions. Basically in my application a user can do many interventions on an incident, and an incident can have interventions by many users. I pass the needed strong parameters, but the application gives the following errors when I try to save: "Incident must exist" and "User must exist". I spent hours on this, and can't figure out what is the problem. Can you please help me? I post the relevant code here:
user.rb (model)
has_many :interventions
has_many :incidents, through: :interventions
incident.rb (model)
has_many :interventions
has_many :users, through: :interventions
intervention.rb (model)
belongs_to :incident_priority
belongs_to :intervention_status
interventions_controller.rb
def new
#incident = Incident.find(params[:incident])
#user = User.find(current_user.id)
#intervention = Intervention.new(:user_id => #user, :incident_id => #incident)
#project = #incident.channel.project
#mirth = Mirth.find_by server_id: #incident.mirth_server_id
end
def create
#incident = Incident.find(params[:incident_id])
#user = User.find(params[:user_id])
#intervention = Intervention.create(intervention_params)
#project = #incident.channel.project
#mirth = Mirth.find_by server_id: #incident.mirth_server_id
respond_to do |format|
if #intervention.save
format.html { redirect_to new_intervention_path(#incident), notice: 'Intervention was successfully created.' }
format.json { render :show, status: :created, location: #intervention }
else
format.html { render :new, incident: :incident_id }
format.json { render json: #intervention.errors, status: :unprocessable_entity }
end
end
end
< .... >
def intervention_params
params.require(:intervention).permit(:user_id, :incident_id, :incident_priority_id, :begin_date, :end_date, :description,
:intervention_status_id, :forwarded_to)
end
In my view (interventions_form.html.erb):
<%= form_for(#intervention) do |f| %>
<% if #intervention.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#intervention.errors.count, "error") %> prohibited this intervention from being saved:</h2>
<ul>
<% #intervention.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group form-inline">
<%= hidden_field_tag :user_id, #user.id %>
<%= hidden_field_tag :incident_id, #incident.id %>
<strong>Interveniente:</strong>
<%= #user.first_name %> <%= #user.last_name %>
</div>
<div class="form-group form-inline">
<%= f.label 'Prioridade' %>
<%= f.collection_select :incident_priority_id, IncidentPriority.all, :id, :description, {}, {class: "form-control"} %>
</div>
<div class="form-group form-inline">
<%= f.label 'Data início intervenção' %>
<%= f.datetime_select :begin_date %>
</div>
<div class="form-group form-inline">
<%= f.label 'Data fim intervenção' %>
<%= f.datetime_select :end_date, :include_blank => true %>
</div>
<div class="form-group form-inline">
<%= f.label 'Observações' %>
<%= f.text_area :description %>
</div>
<div class="form-group form-inline">
<%= f.label 'Estado' %>
<%= f.collection_select :intervention_status_id, InterventionStatus.all, :id, :description, {}, {class: "form-control"} %>
</div>
<div class="form-group form-inline">
<%= f.label 'Encaminhado para:' %>
<%= f.text_area :forwarded_to %>
</div>
<div class="actions" align="right">
<%= link_to 'Voltar', incidents_path(:mirth => #mirth, :project => #project), class: "btn btn-info" %>
<%= f.submit "Gravar", class: "btn btn-info" %>
</div>
I run debug and the values in the hidden_field_tags are correctly filled. Also in the controller the #user and #incident are correctly populated, but #intervention has nil in the foreign keys :user_id and :incident_id.
Thanks in advance!
You need to associate the user and the incident with the intervention.
in your model...
class Intervention
belongs_to :user
belongs_to :incident
in your create method...
def create
#incident = Incident.find(params[:incident_id])
#user = User.find(params[:user_id])
#intervention = Intervention.create(intervention_params)
#intervention.incident = #incident
#intervention.user = #user
...
You need to change this:
def create
#incident = Incident.find(params[:incident_id])
#user = User.find(params[:user_id])
# ...
end
For this:
def create
#incident = Incident.find(params[:incident_id])
#user = User.find(params[:user_id])
intervention_params.merge(user_id: #user.id, incident_id: #incident.id)
# ...
end
And your model:
class Intervention
belongs_to :user
belongs_to :incident
Related
My route :
patch '/projects/:project_id/budgets/:id', to: 'budgets#update', as:'patch_budget' #update
when i send a patch method to this route, :project_id should be my project_id, like:
/projects/test_project/budgets/14
but it turns to budget.id, like:
/projects/14/budgets/14
_form.html.erb
<%= form_with model: budget do |f| %>
<div>
<%= f.label :name, "預算名稱" %><br>
<%= f.text_field :name %>
</div>
<div>
<%= f.label :description, "說明" %><br>
<%= f.text_field :description %>
</div>
<div>
<%= f.label :category, "預算類別" %><br>
<%= f.text_field :category %>
</div>
<div>
<%= f.label :quantity, "數量" %><br>
<%= f.text_field :quantity %>
</div>
<div>
<%= f.label :unit_cost, "單位成本" %><br>
<%= f.text_field :unit_cost %>
</div>
<div>
<%= f.label :issue_id, "議題" %><br>
<%= f.select(:issue_id, Issue.all.collect { |i| [ i.subject, i.id] }) %>
</div>
<div>
<%= f.submit "送出" %>
</div>
<% end %>
edit.html.erb
<h1>編輯預算</h1>
<%= render "form", budget: #budget %>
<br/>
<%= link_to "回預算列表", budgets_path %>
budgets_controller.rb
class BudgetsController < ApplicationController
before_action :find_project, :authorize
def index
#budgets = Budget.all
#sum = Budget.all.sum(:total_cost).round(1)
end
def new
#budgets = Budget.new
end
def create
#budgets = Budget.new(budget_params)
#budgets.project_id = #project.id
#budgets.total_cost = #budgets.quantity * #budgets.unit_cost
#budgets.created_by_id = User.current.id
if #budgets.save
redirect_to budgets_path, notice: "新增預算成功!"
else
render :new
end
end
def edit
#budget = Budget.find(params[:id])
end
def update
#budget = Budget.find(params[:id])
if #budget.update(budget_params)
redirect_to budgets_path, notice: "修改成功!"
else
render :edit
end
end
def destroy
#budget = Budget.find(params[:id])
#budget.destroy if #budget
redirect_to budgets_path, notice: "預算已刪除!"
end
def show
#budget = Budget.find(params[:id])
#create_by = User.find(#budget.created_by_id)
if #budget.modified_by_id != nil
#modified_by = User.find(#budget.modified_by_id)
end
end
private
def find_project
# #project variable must be set before calling the authorize filter
#project = Project.find(params[:project_id])
end
def budget_params
params.require(:budget).permit(:name, :description, :category,
:quantity, :unit_cost, :issue_id)
end
end
Create and delete are running normally, I try many ways in my form, but it didn't work, thanks for the help.
You need to pass an array to generate nested routes:
<%= render "form", budget: #budget, project: #project %>
<%= form_with model: [project, budget] do |f| %>
See https://api.rubyonrails.org/v7.0/classes/ActionDispatch/Routing/PolymorphicRoutes.html
I am using carrierwave and trying to display images of products in the index view. This are my models, controllers and views
product.rb
class Product < ActiveRecord::Base
has_many :order_items
belongs_to :category, required: false
has_many :product_attachments
accepts_nested_attributes_for :product_attachments
mount_uploader :image, ImageUploader
default_scope { where(active: true) }
end
product_attachment.rb
class ProductAttachment < ApplicationRecord
mount_uploader :image, ImageUploader
belongs_to :product
end
products_controller.rb (extract)
class ProductsController < ApplicationController
def index
#products = Product.all
#order_item = current_order.order_items.new
end
def show
#product = Product.find(params[:id])
#product_attachments = #product.product_attachments.all
end
def new
#product = Product.new
#product_attachment = #product.product_attachments.build
#categories = Category.all.map{|c| [ c.name, c.id ] }
end
def create
#product = Product.new(product_params)
#product.category_id = params[:category_id]
respond_to do |format|
if #product.save
params[:product_attachments]['image'].each do |a|
#product_attachment = #product.product_attachments.create!(:image => a, :product_id => #product.id)
end
format.html { redirect_to #product, notice: 'Product was successfully created.' }
else
format.html { render action: 'new' }
end
end
end
private
def product_params
params.require(:product).permit(:name,:price, :active, :description, product_attachments_attributes:
[:id, :product_id, :image], category_attributes: [:category_id, :category])
end
end
index.html.erb
<div class="row">
<div class="col-xs-offset-1 ">
<% #products.each do |product| %>
<%= render "product_row", product: product, order_item: #order_item %>
<% end %>
</div>
_product_row.html.erb
<div class="well">
<div class="row">
<div class="container-fluid row">
<div class="col-md-5 col-lg-5 col-sm-5 col-xs-5 binder">
<br><%= image_tag product.image_url.to_s %><br><br>
</div>
<div class="col-md-4 col-lg-4 col-sm-4 col-xs-4 binder">
<h4 class="text-left"><%= product.name.split.map(&:capitalize).join(' ') %> </h4>
<h4 class="text-left"><span style="color: green"><%= number_to_currency(product.price, :unit => "€") %></span></h4>
<h4><%= link_to Category.find(product.category_id).name, category_path(product.category_id) %></h4>
<h6 class="text-left"><%= link_to 'Delete', product_path(product), method: :delete,
data: { confirm: 'Are you sure?' } %></h6><br><br>
</div>
<div class="col-md-3 col-lg-3 col-sm-3 col-xs-3 binder">
<%= form_for order_item, remote: true do |f| %>
<div class="input-group">
<%= f.number_field :quantity, value: 1, class: "form-control", min: 1 %>
<div class="input-group-btn">
<%= f.hidden_field :product_id, value: product.id %>
<%= f.submit "Add to Cart", class: "btn btn-primary text-right" %>
</div>
</div>
<% end %>
</div>
</div>
</div>
</div>
With <%= image_tag product.image_url.to_s %> the image doesn't appear. When I change it to <%= image_tag product_attachments.first.image_url.to_s %> I get the following error:
undefined local variable or method `product_attachments' for #<#<Class:0x00007f28544ccc68>:0x00007f285dd3aab8>
I am pretty new to Ruby and don't know what I am doing wrong or how to fix this. Any help would be appreciated. I am using Ruby version 2.5.1 and rails 5.2.0 on ubuntu.
I would expect that the following works:
<%= image_tag product.product_attachments.first.image_url.to_s %>
Try this:
image_tag(product.product_attachments.first.image.url.to_s)
It should work. I realized that sometimes image_url doesn't work as expected but image.url does.
If i understand well your snippets, the model you mount the ImageUploader is ProductAttachment (which have the attribute image) so you can remove mount_uploader :image, ImageUploader of your Product model.
The image is mounted on every product_attachments for one product. Just display the images inside the partial by iterating through product_attachments:
<% product.product_attachments.each do |attachment| %>
<%= image_tag(attachment.image.url) %>
<% end %>
I have two models, Roaster and Roast
I want to have the user select the value of :roaster in the new roast form, from the Roaster model. I am using a collection_select which displays the list of roasters in the dropdown ok, but it doesn't insert the value into the table. From the console, it actually looks like it's trying to pass the roaster_id
"roast"=>{"roaster_id"=>"1", "name"=>"Rugby", "beans"=>"", "countries_attributes"=>{"0"=>{"country_name"=>"", "regions_attributes"=>{"0"=>{"region_name"=>""}}}, "1"=>{"country_name"=>"", "regions_attributes"=>{"0"=>{"region_name"=>""}}}, "2"=>{"country_name"=>"", "regions_attributes"=>{"0"=>{"region_name"=>""}}}}, "bestfor"=>"", "roast"=>"", "tastingnotes"=>""}, "commit"=>"Create Roast"}
My select:
<%= form.collection_select(:roaster_id, Roaster.all, :id, :roaster_name, :prompt => 'Select Roaster') %>
I've tried
<%= form.collection_select(:roaster_name, Roaster.all, :id, :roaster_name, :prompt => 'Select Roaster') %>
but this gives and undefined method error.
My roast_params
params.require(:roast).permit(:roaster, :roaster_id, :name, :bestfor, :beans, :roast, :tastingnotes, :notes, :slug, :avatar, countries_attributes: [:country_id, :country_name, regions_attributes: [:id, :region_name]])
Adding in :roaster_name doesn't solve either.
As requested full form:
<%= form_with(model: roast, local: true, multipart: true) do |form| %>
<% if roast.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger" role="alert">
<h2><%= pluralize(roast.errors.count, "error") %> prohibited this roast from being saved:</h2>
<ul>
<% roast.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
<form>
<div class="row">
<div class="col-6">
<div class="field form-group">
<%= form.label :roaster, class: 'control-label' %>
<%= form.collection_select(:roaster_id, Roaster.all, :id, :roaster_name, :prompt => 'Select Roaster') %>
</div>
</div>
<div class="col-6">
<div class="form-group">
<%= form.label :name, class: 'control-label' %>
<%= form.text_field :name, class: "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<%= form.label :beans, "Blend", class: 'control-label' %><br />
<%= form.select :beans, [ 'Single Origin','Two Country Blend', 'Three Country Blend' ], :prompt => 'Select One', id: :roast_beans, class: "form-control" %>
</div>
<div class="row">
<%= form.fields_for :countries do |countries_form| %>
<div class="col-6">
<div class="form-group">
<%= countries_form.label :country %>
<%= countries_form.text_field :country_name, class: "form-control" %>
</div>
</div>
<div class="col-6">
<!-- note the appending of `countries_` to form.fields to allow for deeper nested to work-->
<%= countries_form.fields_for :regions do |regions_form| %>
<%= regions_form.label :region %>
<%= regions_form.text_field :region_name, class: "form-control" %>
<% end %>
<br />
</div>
<% end %>
</div>
<div class="form-group">
<%= form.label :bestfor, "Style", class: 'control-label' %><br />
<%= form.select :bestfor, [ 'Espresso','Filter' ], :prompt => 'Select One', id: :roast_bestfor, class: "form-control" %>
</div>
<div class="form-group">
<%= form.label :roast, "Strength", class: 'control-label' %><br />
<%= form.select :roast, [ 'Light','Medium','Dark' ], :prompt => 'Select One', id: :roast_roast, class: "form-control" %>
</div>
<div class="form-group">
<%= form.label :tastingnotes, "Tasting Notes (separate with commas, e.g chocolate, citrus)", class: 'control-label' %><br />
<%= form.text_area :tastingnotes, id: :roast_tastingnotes, class: "form-control" %>
</div>
<br />
<div class="form-group">
<%= form.label :avatar, "Upload image...", class: 'control-label' %>
<%= form.file_field :avatar %>
</div>
<div class="actions">
<%= form.submit class: "btn btn-success" %> <%= link_to "Cancel", "/roasts", class: "btn btn-secondary"%>
</div>
<% end %>
</form>
roast_controller.rb
class RoastsController < ApplicationController
before_action :set_roast, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, only: [:create, :edit, :update, :destroy]
before_action :set_search
# GET /roasts
# GET /roasts.json
def index
#q = Roast.ransack(params[:q])
#roastsalpha = #q.result.order(:name)
#roastcount = Roast.count(:country)
#roasts = Roast.order(:name).count
#countroastschart = Roast.order("roaster DESC").all
end
# GET /roasts/1
# GET /roasts/1.json
def show
#roast = Roast.friendly.find(params[:id])
#commentable = #roast
#comments = #commentable.comments
#comment = Comment.new
#sameroaster = Roast.where(roaster: #roast.roaster)
#samecountry = Roast.where(country: #roast.country)
#roastcount = Roast.where(roaster: #roast.roaster)
end
# GET /roasts/new
def new
#roast = Roast.new
3.times {#roast.countries.build.regions.build}
end
# GET /roasts/1/edit
def edit
3.times {#roast.countries.build.regions.build}
end
# POST /roasts
# POST /roasts.json
def create
#roast = Roast.new(roast_params)
respond_to do |format|
if #roast.save
format.html { redirect_to #roast, notice: 'Roast was successfully created.' }
format.json { render :show, status: :created, location: #roast }
else
format.html { render :new }
format.json { render json: #roast.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /roasts/1
# PATCH/PUT /roasts/1.json
def update
respond_to do |format|
if #roast.update(roast_params)
format.html { redirect_to #roast, notice: 'Roast was successfully updated.' }
format.json { render :show, status: :ok, location: #roast }
else
format.html { render :edit }
format.json { render json: #roast.errors, status: :unprocessable_entity }
end
end
end
# DELETE /roasts/1
# DELETE /roasts/1.json
def destroy
#roast.destroy
respond_to do |format|
format.html { redirect_to roasts_url, notice: 'Roast was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_roast
#roast = Roast.friendly.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def roast_params
params.require(:roast).permit(:roaster, :roaster_id, :name, :bestfor, :beans, :roast, :tastingnotes, :notes, :slug, :avatar, countries_attributes: [:country_id, :country_name, regions_attributes: [:id, :region_name]])
end
end
I think you are doing many wrong things. By looking your other questions I saw your models. I put some important things:
class Roast < ApplicationRecord
has_many :countries
accepts_nested_attributes_for :countries
end
class Country < ApplicationRecord
has_many :regions, inverse_of: :country
accepts_nested_attributes_for :regions
belongs_to :roast
end
class Region < ApplicationRecord
belongs_to :country, inverse_of: :regions
end
In these models I didn't see the Roaster. I assume a Roast belongs_to :roaster.
So: your Roast has many countries and each country has many regions. But you are passing country names and region names in your view to the create controller. You need to pass the ids, so that you save references to these models.
You have many unnecessary field in params, and some missing ones. This is how it should be:
def roaster_params
params.require(:roast).permit(:roaster_id, :name, :bestfor, :beans, :tastingnotes, :notes, :slug, :avatar, countries_attributes: [:id, regions_attributes: [:id]])
end
You don't need roast, roaster, country_name, region_name. You need the id of the country (and not the country_id), and the id of the region (and not the region_id)
In your form you should ask for country and region ids:
<%= countries_form.collection_select(:id, Country.all, :id, :name, :prompt => 'Select Country') %>
<%= regions_form.collection_select(:id, Region.all, :id, :name, :prompt => 'Select Region') %>
In fact this is more difficult, because a region belongs to a country, but here you are showing all regions. You should only show regions for the selected country (which is dynamic).
i have a problem with my form who contains multiple object
When i go on my page "new" for create new team_member, i have this error :
unknown attribute 'team_member_id' for TeamMembersGame.
models/team_member.rb
class TeamMember < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
has_many :team_members_games
accepts_nested_attributes_for :team_members_games
has_many :team_members_weapons
has_many :team_members_champions
end
models/team_member_game.rb
class TeamMembersGame < ActiveRecord::Base
belongs_to :team_member
end
controllers/admin/team_members_controller.rb
class Admin::TeamMembersController < Admin::DashboardController
def new
#member = TeamMember.new
#member.team_members_games.build
end
def create
#member = TeamMember.new(member_params)
if #member.save
redirect_to edit_admin_team_member_path(#member.id), notice: 'Le membre a bien été creer'
else
render 'new'
end
end
def edit
#member = TeamMember.find(params[:id])
#member_game = #member.team_members_games
##member = TeamMember.joins(:TeamMembersChampion, :TeamMembersWeapon, :TeamMembersGame)
end
def update
#member = TeamMember.find(params[:id])
if #member.update_attributes(member_params)
# Handle a successful update.
redirect_to edit_admin_team_member_path(#member.id), notice: 'Le membre a bien été modifier'
else
render 'edit'
end
end
def destroy
TeamMember.destroy(params[:id])
redirect_to admin_team_members_path, notice: 'Le membre a bien ete supprimer'
end
private
def member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_games: [ :team_members_id, :name_game])
end
def member_games
params.require(:team_members_games).permit(:team_members_id, :name_game)
end
end
view/admin/new.html.erb
<%= form_for(#member, url: admin_team_members_path, html: { method: :post }, id: 'new_news') do |f| %>
<%= #member.inspect %>
<%= #member_games.inspect %>
<div class="row">
<div class="col s12">
<% #member.errors.full_messages.each do |msg| %>
<%= msg %>
<% end %>
</div>
</div>
<div class="row">
<div class="col s12 m6">
<div class="field input-field">
<%= f.label :name, "Nom" %>
<%= f.text_field :name, autofocus: true, :class => "" %>
</div>
</div>
</div>
<div class="row">
<div class="col s12">
<p class="bold">
Jeux :
</p>
</div>
<div class="col s12 m6">
<%= f.fields_for :team_members_games do |team_members_games_form| %>
<div class="field input-field">
<%= team_members_games_form.check_box :name_game, {:class => "filled-in", :id => "team_members_game_name_game"}, true, false %>
<%= team_members_games_form.label :name_game, "game" %>
</div>
<% end %>
</div>
</div>
<div class="row">
<div class="col s12">
<div class="btnlog actions">
<%= button_tag(type: 'submit', class: "btn") do %>
Publier <i class='material-icons right'>send</i>
<% end %>
</div>
</div>
</div>
<% end %>
thanks !
you are permitting team_members_id in your code instead of team_member_id
refactor your code to this:
def member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_games_attributes: [ :id, :team_member_id, :name_game])
end
Change permitted method name and parameters like this:-
def team_member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_games: [ :id, :name_game])
end
And use this method while creating team member:-
def create
#member = TeamMember.new(team_member_params)
if #member.save
redirect_to edit_admin_team_member_path(#member.id), notice: 'Le membre a bien été creer'
else
render 'new'
end
end
I have corrige some errors, but i haven't idea for get the id of team_member for the table team_member_games :
def team_member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_game_attributes: [ :id, :name_game])
end
no one element are add in my table team_members_games
I'm trying to build a small expense tracking app. Using the nested_form gem to add line items. There is an Expense model which accepts nested attributes. Items belong to expenses and there is a foreign key association. Here's the expense controller:
class ExpensesController < ApplicationController
def new
#expense = Expense.new
#item = #expense.items.build
end
def index
#expenses = Expense.all
##items = Item.where(:expense_id => #expense.id)
end
def show
#expense = Expense.find(params[:id])
#items = Item.where(:expense_id => #expense.id)
end
def create
#expense = Expense.new(expense_params)
respond_to do |format|
if #expense.save
format.html { redirect_to #expense, notice: 'Expense Report Submitted.' }
format.json { render :show, status: :created, location: #expense }
else
format.html { render :new }
format.json { render json: #expense.errors, status: :unprocessable_entity }
end
end
end
def edit
#expense = Expense.find(params[:id])
end
def update
#expense = Expense.find(params[:id])
if #expense.save(expense_params)
flash[:notice] = "Expense Report Updated"
redirect_to #expense
else
render 'edit'
end
end
def destroy
#expense = Expense.find(params[:id])
#expense.destroy
redirect_to 'root'
end
private
def expense_params
params.require(:expense).permit(:department_id, :expense_type_id, :notes, items_attributes: [:id, :description, :amount, :issue_date, :_destroy])
end
end
The form looks like:
<%= nested_form_for (#expense) do |f| %>
<% if #expense.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#expense.errors.count, "error") %> prohibited
this expense from being saved:</h2>
<ul>
<% #expense.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class"row">
<div class="col-md-8">
<div class="form-group">
<%= f.label :department_id %><br>
<%= f.collection_select(:department_id, Department.all, :id, :department_name, prompt: true, class: "dropdown-menu") %>
</div>
<div class="form-group">
<%= f.label :expense_type_id %><br>
<%= f.collection_select(:expense_type_id, ExpenseType.all, :id, :expense_name, prompt: true, class: "form-control") %>
</div>
<%= f.fields_for :items do |i| %>
<div class="form-group">
<%= i.label :description%>
<%= i.text_field :description, class: "form-control" %>
</div>
<div class="form-group">
<%= i.label :amount%>
<%= i.text_field :amount, class: "form-control" %>
</div>
<div class="form-group">
<%= i.label :issue_date%>
<%= i.date_select :issue_date, class: "form-control" %>
</div>
<%= i.link_to_remove "Remove", class: "btn btn-default" %>
<% end %>
<div><p><%= f.link_to_add "Add Expense", :items, class: "btn btn-default" %></p></div>
<div class="form-group">
<%= f.label :notes %>
<%= f.text_area :notes, class: "form-control" %>
</div>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
</div>
</div>
When I hit submit, the expense and items are saved. I checked with Sqlite browser and the foreign key values are captured for each item.
The index file looks like:
<% #expenses.each do |expense| %>
<tr>
<td><%= expense.item.description %></td>
<td><%= number_to_currency(expense.item.amount) %></td>
<td><%= expense.item.issue_date %></td>
<% end %>
I tried the usual combinations (like expense.item.description) by passing through a block, but they aren't working. I would like to know how to display the expense and the associated items in the show and index pages.
Looking at your new action, in your models you would have
class Expense < ActiveRecord::Base
has_many :items
accepts_nested_attributes_for :items
end
So when you are doing expense.items in your view it gives you an active record relation(since expense has many items), try this:
<% #expenses.each do |expense| %>
<% expense.items.each do |item| %>
<tr>
<td><%= item.description %></td>
<td><%= number_to_currency(item.amount) %></td>
<td><%= item.issue_date %></td>
</tr>
<% end %>
<% end %>