I am new to ruby and I am trying to put together a form that will allow you to add items to an order. The form will need to take a quantity for each item in the order.
class Order < ActiveRecord::Base
belongs_to :restaurant
has_many :selections
has_many :items, :through =>:selections;
end
class Selection < ActiveRecord::Base
belongs_to :order
belongs_to :item
end
class Item < ActiveRecord::Base
belongs_to :menu
has_many :selections
has_many :orders, :through => :selections
end
class Restaurant < ActiveRecord::Base
has_many :orders
has_many :menus
has_many :items, :through => :menus
end
class Menu < ActiveRecord::Base
belongs_to :restaurant
has_many :items
end
order controller
# GET /orders/new
def new
#order = Order.new
#restaurant.items.all.each do |item|
#order.selections.build
end
end
orders/_form.html.erb :
The form is supposed to list out the available items and allow you to enter the quantity for an item.
<%= form_for [#restaurant,#order], :html => { :class => 'form-horizontal' } do |f| %>
<div class="control-group">
<%= f.label :current_table, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :current_table, :class => 'text_field' %>
</div>
</div>
<% f.fields_for :selections do |ff| %>
<div class="control-group">
<%= ff.label :quantity, :class => 'control-label' %>
<div class="controls">
<%= ff.text_field :quantity, :class => 'text_field' %>
</div>
</div>
<% end%>
<div class="form-actions">
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
course_orders_path, :class => 'btn' %>
</div>
<% end %>
When I try to render the page I get the following error:
undefined method `quantity' for
<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Selection:0x007ffa0287cd60>
I realize this is probably because I haven't initialized any selections but I'm not entirely sure how/where I should do that. When the form is submitted I want to create an order with a selection for each of the non-empty quantities.
So my first question is how do I construct my form so that I can take a quantity for each item that I know about?
Do I need to initialize anything in the order controller to make this work?
Can you give me any advice or point me to a tutorial that shows me how to set up the create method of the order controller?
EDIT:
I added some code to the Order controller and the form, so when I render the page I no longer get an error, but none of my 'selection' fields rendered. I confirmed with some logging and the debugger that I correctly 'build' 4 selections so I would expect those form elements show up.
Any ideas would be appreciated.
Are you missing a
accepts_nested_attributes_for :nested_class
somewhere?
Also, I had to do something like
<%= form_for [#restaurant,#order] do |f| %>
...
<%= f.fields_for :selections, #order.selections do |ff| %>
...
<% end %>
...
<% end %>
Related
I have three models in my rails 5 application... What I want to do is to be able to create a note on the person's "show" view, then the note should automatically link to that person and any other person I choose to attach the note to.
Here's where I got up to
Note
class Note < ApplicationRecord
has_many :person_notes
has_many :people, through: :person_notes
accepts_nested_attributes_for :person_notes
end
Person Note (Join table)
class PersonNote < ApplicationRecord
belongs_to :person
belongs_to :note
end
Person
class Person < ApplicationRecord
has_many :person_notes
has_many :notes, through: :person_notes
accepts_nested_attributes_for :person_notes
accepts_nested_attributes_for :notes
end
In my "show" section of my "people" controller I have the following:
def show
#notep = Note.new()
#person.notes << #notep
end
This is creating a join of a new note to my person record every time I open the page (obviously i only want the join to happen on the note I have created.)
I have rendered this in a modal as a partial in my "show" view (there is an "end" and a submit button but it's in between 3 divs and I know they weren't the cause of the issue so i didn't include them.:
<%= simple_form_for(#notep, remote: true) do |f| %>
<%= f.error_notification %>
<%= f.input :subject %>
<%= f.input :note %>
<%= f.input :date, html5: true %>
<div class="input-field">
<%= f.check_box :isalert, :id => "alert" %>
<%= f.label :isalert, :for => "alert" %>
</div>
<div class="input-field">
<%= f.check_box :archived, :id => "archived" %>
<%= f.label :archived, :for => "archived" %>
</div>
<div class="input-field">
<%= f.check_box :deleted, :id => "deleted" %>
<%= f.label :deleted, :for => "deleted" %>
</div>
<%= f.input :datecreated, html5: true %>
<%= f.input :user_id %>
<%= f.simple_fields_for :person_notes do |builder| %>
<%= builder.association :person, label_method: :lstfstfullname %>
<%= builder.input :deleted %>
<%= builder.input :datecreated, html5: true %>
<%= builder.input :user_id %>
<% end %>
You can probably tell I'm a total newb, but I'd appreciate any help I can get.
Thanks,
Leah
If I'm understanding this correctly, you'll want a separate Notes controller and create action to handle note creation. Then in your People show view, you can add a form and input field that submits to NotesController#create.
class Project
has_many :project_questions, dependent: :destroy#, through: :projects
accepts_nested_attributes_for :project_questions
end
I am trying to make an app with rails 4 and Simple Form.
I have models called projects, project_questions and project_answers.
The associations between them are:
Projects:
has_many :project_questions, dependent: :destroy#, through: :projects
accepts_nested_attributes_for :project_questions
Project questions:
belongs_to :project#, counter_cache: true
has_many :project_answers, dependent: :destroy
belongs_to :user
accepts_nested_attributes_for :project_answers
belongs_to :user
Project answers:
belongs_to :project_question#, counter_cache: true
belongs_to :user
User:
has_many :project_questions
has_many :project_answers
class ProjectQuestions
belongs_to :project#, counter_cache: true
has_many :project_answers, dependent: :destroy
belongs_to :user
accepts_nested_attributes_for :project_answers
end
ProjectAnswer:
belongs_to :project_question#, counter_cache: true
belongs_to :user
My objective is to have a partial on my projects show page which displays the questions and their answers relating to the project and to have a link to another form where you can ask a question or answer one. I am struggling.
In my controllers I have:
Projects:
def project_params
params.require(:project).permit(project_question_attributes: [:title, :content, :user_id, :project_id,project_answer_attributes: [:answer, :project_question_id]],
Project_question:
def new
#project_question = ProjectQuestion.new
#project_id = params[:project_id]
#project_question.project_answers[0] = ProjectAnswer.new
end
Project_answer:
def new
#project_answer = ProjectAnswer.new
end
def project_question_params
params[:project_question].permit(:id, :title, :content, :project_id, :user_id,project_answer_atttibutes: [:id, :answer, :project_question_id, :user_id])
end
Then in my views I have:
Project#show:
<% if current_user.id == #project.creator_id %>
<%= link_to 'Ask a question', new_project_project_question_path(:project_id => #project.id) %>
<% end %>
<%= render 'project_questions/pqps' %>
Project_question#pqps (a partial):
<div class="containerfluid">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="categorytitle">
<%= #project_question.try(:title) %>
</div>
<div class="generaltext">
<%= #project_question.try(:content) %>
</div>
<span class="editproject">
<% if current_user.id == #project.creator_id %>
<% end %>
</span>
</div>
</div>
</div>
My project_questions form partial is:
<div class="containerfluid">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<% f.simple_fields_for :project_questions do |f| %>
<%= f.input :project_id, as: :hidden, input_html: {value: #project_question_id} %>
<%= f.input :title, label: 'Question:', :label_html => {:class => 'categorytitle'}, placeholder: 'Type your question here', :input_html => {:style => 'width: 100%', class: 'categorytitle'} %>
<%= f.input :content, label: 'Is there any context or other information?', :label_html => {:class => 'categorytitle'}, placeholder: 'Context might help to answer your question', :input_html => {:style => 'width: 100%', rows: 5, class: 'generalprojecttext'} %>
<%= f.button :submit %>
<% end %>
</div>
</div>
</div>
Project_answer#pa (a partial):
(not yet written - still trying to get the questions to work)
My routes are:
resources :projects do
resources :project_questions do
resources :project_answers
end
end
When I try this, I get an error in my project_questions form that says:undefined local variable or methodf' for #<#:0x000001013d8298>`
I can't see where it is talking about f outside the form block. I have tried adding another line to the form for simple_fields for project and then nesting the project questions form inside of it, but that doesn't change anything.
Can anyone see what I've done wrong?
Thank you
You should change this line <% f.simple_fields_for :project_questions do |f|
%> to this <%= simple_form_for :project_questions do |f| %> in order to make it work.
The plataformatec simple_form wiki has a pretty good instructional page on using nested forms.
(Just as a side note, I find that it's often easier to diagnose problems without using partials. Once everything is working, you can clean-up by refactoring into partials.)
I believe you need to pass a local variable to your partial, so it knows what the first "f" refers to.
<%= render 'project_questions/pqps', locals: {f: f} %>
(You also may choose to use a different local variable in the partial for project_questions, just so you're always clear what is being referenced in error messages.)
I'm new to rails and just cant get that problem solved.
i have 3 models. Orders, Products and LineItems.
I want to have a order form with checkboxes for each product. User selects appropriate products and submits the order.
I cannot get the form to create the correct hash.
class Order < ActiveRecord::Base
attr_accessible :account_id, :user_id
has_many :line_items, :dependent => :destroy
end
class LineItem < ActiveRecord::Base
attr_accessible :account_id, :product_id, :order_id
belongs_to :orders
belongs_to :product
end
Here the view:
<%= form_for 'line_items[]' do |f| %>
<%= f.select :account_id, options_from_collection_for_select( Account.all,
:id, :name ), :prompt => 'Select Account' %>
<% Product.all.each do |product| %>
<div>
<%= check_box_tag 'line_items[product_ids][]', product.id %>
</div>
<% end -%>
<div>
<%= f.submit 'save' %>
</div>
thanks!
You would need to use accepts_nested_attributes_for in your model to enable nested atributes from associated models. You may also want to check out this railscast and adapt to your needs.
For example in the orders model:
class Order < ActiveRecord::Base
attr_accessible :account_id, :user_id
has_many :products #This makes the association to products
has_many :line_items, :dependent => :destroy
accepts_nested_attributes_for :products #This allows the attributes from products accessible
end
Then the form could be:
<%= form_for #order do |f| %>
<%= f.select :account_id, options_from_collection_for_select( Account.all,
:id, :name ), :prompt => 'Select Account' %>
<%= f.fields_for :product do |product_form| %>
<%= product_form.check_box :id %>
<% end %>
<%= f.submit %>
<% end %>
I have a habtm model like:
class Recurrence < ActiveRecord::Base
has_many :participations, :include => :user
has_many :users, :through => :participations
accepts_nested_attributes_for :participations
attr_accessible :scheduled_to, :user_id, :user_ids
end
class Participation < ActiveRecord::Base
belongs_to :recurrence
belongs_to :user
attr_accessible :recurrence_id, :user_id
end
class User < ActiveRecord::Base
has_many :participations, :dependent => :delete_all
has_many :recurrences, :through => :participations
accepts_nested_attributes_for :participations
attr_accessible :name, :email, :phone, :recurrence_ids
end
with standard actions for the recurrences_controller (index, show, new, edit, create, update, destroy).
In the view of a single recurrence (/recurrences/10 -> show-action), I try to create/update the participation of user. When I do in the mentioned view something like:
<%= form_for #recurrence do |f| %>
<div class="checkbox">
<% for user in User.find(:all) %>
<div>
<%= check_box_tag "recurrence[user_ids][]", user.id, #recurrence.users.include?(user) %>
<%= user.name %>
</div>
<% end %>
</div>
<div class="actions">
<%= f.submit "Update", :class => 'btn btn-mini btn-primary' %>
</div>
<% end %>
erverything is working fine, I can add or remove the participation for one or more users.
BUT I like to do it - for just a single user, namely the current_user! I tried with the following source:
<%= form_for(#recurrence) do %>
<%= check_box_tag "recurrence[user_id]", current_user.id,
#recurrence.users.include?(current_user) %>
<%= current_user.name %>
<%= submit_tag "Update" %>
<% end %>
which is not working, more detailed
Updating the not changed status: not particpating, doesn't do anything: correct!
Changing status: from not participating - to participating, works for current_user, BUT will also delete the status of a other users: wrong!
Changing status: from participating - to not participating, won't change anything: wrong!
Any help is welcome!
Finaly I want to reduce the Check-Box to Confirm-/Refuse-Buttons with hidden-fields for the recurrence, but proabably there is easier rails-way?
I have recipe and ingredient in a many to many relation.
I have defined the following commands in my presentation.
<div>
<%= render :partial => 'ingredients/form',
:locals => {:form => recipe_form} %>
</div>
the partial begins with
<%= form_for(#ingredient) do |ingredient_form| %>
but received #ingredient nill.
Then I tried
<%= recipe_form.fields_for :ingredients do |builder| %>
<%= render 'ingredient_fields', f: builder %>
<% end %>
where my render was
<p class="fields">
<%= f.text_field :name %>
<%= f.hidden_field :_destroy %>
</p>
but nothing was printed.
then I tried
<% #recipe.ingredients.each do |ingredient| %>
<%= ingredient.name %>
<% end %>
and only then all of the ingredients were printed.
What was I doing wrong in the previous tries ?
Thank you.
my ingredient recipe relation defined as follows
class Ingredient < ActiveRecord::Base
has_many :ingredient_recipes
has_many :recipes, :through => :ingredient_recipes
...
class Recipe < ActiveRecord::Base
has_many :ingredient_recipes
has_many :ingredients, :through => :ingredient_recipes
...
accepts_nested_attributes_for :ingredient_recipes ,:reject_if => lambda { |a| a[:content].blank?}
class IngredientRecipe < ActiveRecord::Base
attr_accessible :created_at, :ingredient_id, :order, :recipe_id
belongs_to :recipe
belongs_to :ingredient
end
You don't exactly specify what you are trying to do, so I am presuming you have a page that shows a recipe, with many ingredients that can be edited and added to. In your controller you have something like:
class RecipeController < ApplicationController
def edit
#recipe = Recipe.find(params[:id]
end
end
I am also presuming that you are looking to have a form that post backs to the create action. I therefore think you want a form like this:
<%= form_for #recipe do |form| %>
<%= label_for :name %>
<%= text_field :name %>
<%= form.fields_for :ingredients do |ingredients_fields| %>
<div class="ingredient">
<%= f.text_field :name %>
<%= f.hidden_field :_destroy %>
</div>
<% end %>
<% end %>
Also, change your recipe to accept nested attributes for ingredients, not ingredient_recipes:
class Recipe < ActiveRecord::Base
has_many :ingredient_recipes
has_many :ingredients, :through => :ingredient_recipes
...
accepts_nested_attributes_for :ingredients, :reject_if => lambda { |a| a[:content].blank?}
And finally, add attr_accessible for your content:
class Ingredient < ActiveRecord::Base
attr_accessible :content
...
Does that work for you?