I am building an application to manage debts and am trying to create three objects using the same form.
The models are;
Debt (the amount owed)
class Debt < ActiveRecord::Base
belongs_to :user
belongs_to :creditor
belongs_to :debtor
accepts_nested_attributes_for :debtor, :creditor
end
Debtor (The person who owes)
class Debtor < ActiveRecord::Base
belongs_to :user
has_many :debts
end
Creditor (The person who is owed)
class Creditor < ActiveRecord::Base
belongs_to :user
has_many :debts
end
I am using the new debt form and would like to show fields for debtor and creditor. So when a new debt is created, so is the associated debtor and creditor.
I have viewed the documentation however, cannot get the fields for debtor or creditor to display on the form.
This is the form
<%= simple_form_for(#debt) do |f| %>
<%= f.error_notification %>
<!-- Debt fields -->
<div class="form-inputs">
<%= f.association :user %>
<%= f.input :amount %>
<%= f.input :commission %>
<%= f.input :invoice_issued %>
<%= f.input :invoice_date %>
<%= f.input :status %>
<%= f.input :details %>
</div>
<!-- Debtor Fields -->
<ul>
<%= f.fields_for :debtor do |debtor_form| %>
<li>
<%= debtor_form.association :user %>
<%= debtor_form.input :business_name %>
<%= debtor_form.input :abn %>
<%= debtor_form.input :first_name %>
<%= debtor_form.input :last_name %>
<%= debtor_form.input :email %>
<%= debtor_form.input :mobile_number %>
<%= debtor_form.input :phone_number %>
</li>
<% end %>
</ul>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
Any help is appreciated.
EDIT
create_table "debts", force: :cascade do |t|
t.integer "user_id"
t.float "amount"
t.float "commission"
t.boolean "invoice_issued"
t.date "invoice_date"
t.string "status"
t.text "details"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
You need to build your debt's debtor or creditor in your controller:
#controller
def new
#debt = Debt.new
#debt.build_debtor
#bebt.build_creditor
end
Related
I am trying to create a many-to-many table relationship in a Rails 5 project.
One Shop can have many Categories, which are indexed in the Shop_Categories table.
I seem to be missing one key step though. When I submit my Shop form, I receive the soft error: "Unpermitted parameter: :shop_category"
I can see my shop_category parameters being successfully sent in the Rails server log, but the Shop_Categories table doesn't get updated at all.
What am I missing, and what can I change so that pressing save on the Shop view form updates the Shop_Categories table?
Here's my code.
Shop Model
class Shop < ApplicationRecord
belongs_to :type
has_many :shop_categories
has_many :categories, through: :shop_categories
accepts_nested_attributes_for :shop_categories
enum status: [:open, :closed, :opening_soon, :closing_soon]
end
Shop_Category Model
class ShopCategory < ApplicationRecord
belongs_to :shop
belongs_to :category
end
Category Model
class Category < ApplicationRecord
has_many :subcategories, dependent: :destroy
has_many :shop_categories
has_many :shops, through: :shop_categories
end
Shop Controller (Excerpt)
def new
#shop = Shop.new
#shop.shop_categories.build
end
def create
#shop = Shop.new(shop_params)
#shop.open_date = params[:shop][:open_date]+"-01"
#shop.close_date = params[:shop][:close_date]+"-01"
if #shop.save
redirect_to #shop
else
render 'new'
end
end
def update
#shop = Shop.find(params[:id])
if #shop.update(shop_params)
redirect_to #shop
else
render 'edit'
end
end
private
def shop_params
params[:shop][:open_date] = params[:shop][:open_date]+"-01"
params[:shop][:close_date] = params[:shop][:close_date]+"-01"
params.require(:shop).permit(:shop_name, :type_id, :status,
:phone_number, :mobile_number, :email_address, :open_date,
:close_date, shop_categories_attributes: [ :shop_id, :category_id] )
end
Shop Form View (Excerpt)
<p>
<%= form.label :shop_name %><br>
<%= form.text_field :shop_name %>
</p>
<%= form.fields_for :shop_category do |category_fields| %>
<p>
<%= category_fields.label :category %><br />
<%= category_fields.collection_select(:category_id, Category.all, :id, :category_name, include_blank: true) %>
</p>
<% end %>
<p>
<%= form.submit %>
</p>
And finally, the Database Schema
create_table "categories", force: :cascade do |t|
t.string "category_name"
t.text "category_description"
t.string "visible_category"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "shop_categories", force: :cascade do |t|
t.string "visible_category_override"
t.integer "shop_id"
t.integer "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["category_id"], name: "index_shop_categories_on_category_id"
t.index ["shop_id"], name: "index_shop_categories_on_shop_id"
end
create_table "shops", force: :cascade do |t|
t.string "shop_name"
t.integer "status"
t.integer "sale"
t.string "phone_number"
t.string "mobile_number"
t.string "email_address"
t.date "open_date"
t.date "close_date"
t.integer "type_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["type_id"], name: "index_shops_on_type_id"
end
Any suggestions would be greatly appreciated. I just can't work out which piece of the puzzle I'm missing!
Update: Including the Dev log, and the full Shop Form.
Dev Log
Started PATCH "/shops/1" for 127.0.0.1 at 2018-01-14 11:08:39 +0000
Processing by ShopsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"2qydDj9JovMrg9VT6Lo5xbcNSHl5MH0ylmq3IMMX4iRTAVSgK6JlXWpG+CyuwQK6svZJn9wtnEnZANUlOZYzXA==",
"shop"=>{"shop_name"=>"test", "type_id"=>"1",
"shop_categories"=>{"category_id"=>"1"}, "subcategory_id"=>"",
"status"=>"open", "phone_number"=>"123", "mobile_number"=>"13212",
"email_address"=>"hello#test.com", "open_date"=>"2017-12",
"close_date"=>"2017-12"}, "commit"=>"Update Shop", "id"=>"1"}
Shop Load (0.5ms) SELECT "shops".* FROM "shops" WHERE "shops"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Unpermitted parameters: :shop_categories, :subcategory_id
(0.1ms) begin transaction
Type Load (0.2ms) SELECT "types".* FROM "types" WHERE "types"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.1ms) commit transaction
Redirected to http://localhost:3000/shops/1
Completed 302 Found in 10ms (ActiveRecord: 0.9ms)
Full view/shops/_form.html.erb file
<%= form_with model: #shop, local: true do |form| %>
<% if #shop.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(#shop.errors.count, "error") %> prohibited
this shop from being saved:
</h2>
<ul>
<% #shop.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= form.label :shop_name %><br>
<%= form.text_field :shop_name %>
</p>
<p>
<%= form.label :type %><br />
<%= form.collection_select(:type_id, Type.all, :id, :type_name) %>
</p>
<%= form.fields_for :shop_categories do |category_fields| %>
<p>
<%= category_fields.label :category %><br />
<%= category_fields.collection_select(:category_id, Category.all, :id, :category_name, include_blank: true) %>
</p>
<% end %>
<p>
<%= form.label :subcategory %><br />
<%= form.grouped_collection_select :subcategory_id, Category.all, :subcategories, :category_name, :id, :visible_subcategory, include_blank: true %>
</p>
<p>
<%= form.label :status %><br />
<%= form.select :status, Shop.statuses.keys %>
</p>
<p>
<%= form.label :phone_number %><br>
<%= form.telephone_field :phone_number %>
</p>
<p>
<%= form.label :mobile_number %><br>
<%= form.telephone_field :mobile_number %>
</p>
<p>
<%= form.label :email_address %><br>
<%= form.email_field :email_address %>
</p>
<p>
<%= form.label :open_date %><br>
<%= form.month_field :open_date %>
</p>
<p>
<%= form.label :close_date %><br>
<%= form.month_field :close_date %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
It should probably be :shop_categories, not :shop_category
<%= f.fields_for :shop_categories do |category_f| %>
...
<% end %>
You also kind of lost me in the Shop_Category Model part. The actual class name is different (ShopSubcategory) and it belongs_to a subcategory? This will probably cause some errors as well. I guess what you meant is the ShopCategoryjoin model and it belongs_to :category
Update
Also be sure to build your nested resource when creating a new form:
#shop_controller
def new
#shop = Shop.new
#shop.shop_categories.build
...
end
Im new to ror so sorry if that's a really basic question.
So, in my app i have quizzes and each quiz, beside questions and answers, should have 5 links.
class Quiz < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :questions
has_many :links
end
class Link < ActiveRecord::Base
belongs_to :quizzes
end
Schema looks like this:
create_table "links", force: true do |t|
t.string "name"
t.string "www"
t.integer "quiz_id"
end
create_table "questions", force: true do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "quiz_id"
end
create_table "quizzes", force: true do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
end
Now, in views I want to add links as i Add/Edit my quiz.
View for form looks like this:
<%= form_for(#quiz) do |f| %>
<% if #quiz.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#quiz.errors.count, "error") %> prohibited this quiz from being saved:</h2>
<ul>
<% #quiz.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br>
<%= f.text_field :content %>
<%= **THIS IS PLACE FOR TEXT FIELD FOR LINK_NAME AND LINK_WWW** %>
</div>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
How do I create a form to add the links?
You can use fields_for:
<%= f.label :content %><br>
<%= f.text_field :content %>
<%= f.fields_for #quiz.links.new do |ff| %>
<%= ff.label :name %>
<%= ff.text_field :name %>
<% end %>
And allow the Quiz to update the Link records associated:
class Quiz < ActiveRecord::Base
accepts_nested_attributes_for :links
I have problem because when I try to add data to my database using form I get error unknown_attribute id_lekarza (the same with id_pacjenta and id_poradni) and I don't know why, please help
Form:
<div id="container">
<%= form_for(#refferal) do |f| %>
<div class="field">
<%= f.label :rodzaj_badania %><br />
<%= f.text_field :rodzaj_badania, placeholder: "Podaj jakie badanie ma byc wykonane", size: 35 %>
</div>
<div class="field">
<%= f.label :ilosc_badan %><br />
<%= f.number_field :ilosc_badan, placeholder: "Wpisz ilosc badan" %>
</div>
<div class="field">
<%= f.label :opis %><br />
<%= f.text_field :opis, placeholder: "Podaj krótki opis dla pracownika rejestracji/laboratorium", size: 50%>
</div>
<div class="field">
<%= f.label :data %><br />
<%= f.datetime_select :data, placeholder: "Podaj termin badania" %>
</div>
<div class="field">
<%= f.hidden_field :id_lekarza, :value => Doctor.find(session[:current_doctor_id]).id %>
</div>
<div class="field">
<%= f.hidden_field :id_pacjenta, :value => Patient.find(session[:current_patient_id]).id %>
</div>
<div class="field">
<%= f.hidden_field :id_poradni, :value => Clinic.find(session[:current_clinic_id]).id %>
</div>
<div class="actions">
<%= f.submit "Utwórz skierowanie" %>
</div>
<% end %>
</div>
Model:
class Refferal < ActiveRecord::Base
attr_accessible :data, :id_lekarza, :id_pacjenta, :id_poradni, :id_pracownika, :ilosc_badan, :opis, :rodzaj_badania
belongs_to :patient
belongs_to :employee
belongs_to :clinic
belongs_to :doctor
has_many :laboratoria
end
Schema:
create_table "refferals", force: true do |t|
t.string "rodzaj_badania"
t.integer "ilosc_badan"
t.string "opis"
t.datetime "data"
t.integer "id_lekarza"
t.integer "id_pacjenta"
t.integer "id_pracownika"
t.integer "id_poradni"
t.datetime "created_at"
t.datetime "updated_at"
end
It looks like your belongs_to associations might be your problem. Rails is really opinionated about what it expects you to name things. If your model belongs to a doctor (which is the case with Refferal model), Rails is expecting the attribute to be called doctor_id.
Try this:
Change the attribute names from :id_lekarza to :lekarza_id, and so forth for the others. Then change your model associations to specify the actual class those attributes belong to:
class Refferal < ActiveRecord::Base
attr_accessible :data, :id_lekarza, :id_pacjenta, :id_poradni, :id_pracownika, :ilosc_badan, :opis, :rodzaj_badania
belongs_to :pacjenta, class_name: 'Patient'
belongs_to :employee
belongs_to :poradni, class_name: 'Clinic'
belongs_to :lekarza, class_name: 'Doctor'
has_many :laboratoria
end
Also, you'll probably want to change your has_many association to the plural: has_many :laboratorias
Good luck!
I do not know clearly but my suspicion is that ID is probably reserved for references.
Try renaming the fields from;
id_lekarza, id_pacjenta , id_pracownika, id_poradni
to
lekarza, pacjenta , pracownika, poradni
This is what I have:
post.rb:
class Post < ActiveRecord::Base
has_many :replies, :dependent => :destroy
accepts_nested_attributes_for :replies, :allow_destroy => true
end
reply.rb:
class Reply < ActiveRecord::Base
belongs_to :post
end
posts/_reply_fields.html.erb:
<p>
<%= f.label :content, "Reply" %><br />
<%= f.text_area :content, :rows => 3 %><br />
</p>
posts/_form.html.erb:
<%= form_for(#post) do |f| %>
<% if #post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br>
<%= f.text_field :content %>
</div>
<div class="field">
<%= f.label :user %><br>
<%= f.text_field :user %>
</div>
<div class="replies">
<% f.fields_for :replies do |builder| %>
<%= render 'reply_fields', :f => builder %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
schema.rb:
create_table "posts", force: true do |t|
t.string "content"
t.string "user"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "replies", force: true do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "post_id"
end
The output in the replies parts is just:
<div class="replies">
</div>
The reply fields are not showing up at all. What could be the problem?
<div class="replies">
<%= f.fields_for :replies do |builder| %>
<%= render 'reply_fields', :f => builder %>
<% end %>
</div>
Further to the comment & answer, you also need to build the replies ActiveRecord objects:
#app/controllers/posts_controller.rb
def new
#post = Post.new
#post.replies.build
end
I have two models, Ingredients and Foods:
class Food < ActiveRecord::Base
belongs_to :user
has_many :ingredients
accepts_nested_attributes_for :ingredients
attr_accessible :name, :price
end
class Ingredient < ActiveRecord::Base
belongs_to :user
belongs_to :food
attr_accessible :ingredient_name, :quantity_used
end
The schemas for the two models are as follows:
create_table "foods", :force => true do |t|
t.string "name"
t.integer "user_id"
t.float "price"
t.string "ingredient_name"
end
create_table "ingredients", :force => true do |t|
t.string "ingredient_name"
t.integer "user_id"
t.integer "food_id"
t.integer "quantity_used"
end
I'm creating a form for Food which also creates/updates the Ingredient table as well. I have the form working, and the submit button updates the correct attributes, but I have other attributes in each table that I want to update as well. For example, in the Food Controller, I want to do something like ingredient.user_id = current_user.id. I understand I can access things through params[:food], but how do I access individual fields which aren't being updates by the form?
Right now, my form is:
<%= form_for(#food) do |f| %>
<div class="field">
<%= f.label :Name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :price %><br />
<%= f.number_field :price %>
</div>
<div>
<%= f.fields_for :ingredients do |builder| %>
<%= builder.label "Ingredient Used:" %>
<%= builder.text_field :ingredient_name %><br />
<%= builder.label "Quantity Used:" %>
<%= builder.text_field :quantity_used %><br />
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
How do I access this specific Food's ingredients in the Food#create action?
Thanks!
You might need to add :ingredients_attributes to attr_accessible in your Food model.
You can mess about with the params hash in the controller by iterating over the :ingredients_attributes or you can use assign_attributes.