build nested attribute if it exists increase quantity by 1 - ruby-on-rails

I have my form setup like this:
<%= simple_form_for #line_item do |f| %>
<%= f.input :product_id, as: :hidden, input_html: { value: #product.id } %>
<%= f.simple_fields_for :line_item_attributes do |attributes_form| %>
<%= attributes_form.association :product_attribute, collection: #product.product_attributes %>
<% end %>
<%= f.button :submit %>
<% end %>
and my create action looks like this:
def create
product = Product.find(params[:line_item][:product_id])
#line_item = #cart.line_items.build(product: product)
respond_to do |format|
if #line_item.save
format.html { redirect_to #line_item, notice: 'Line item was successfully created.' }
format.json { render :show, status: :created, location: #line_item }
else
format.html { render :new }
format.json { render json: #line_item.errors, status: :unprocessable_entity }
end
end
end
now I'd essentially like to expand it so I can build the nested attributes for line_item. The small catch is if the item exists already I wish for the record not to be created, but instead += 1. I'm thinking I have to maybe create a method, anyone have any ideas?

You might not need extra method.
def create
product = Product.find(params[:line_item][:product_id])
#line_item = #cart.line_items.build do |line_item|
line_item.product = product
line_item.product_attribute = ProductAttribute.where(...).first || line_item.build_product_attribute()
end
...
end
The line line_item.product_attribute = ProductAttribute.where(...).first || line_item.build_product_attribute() assigns existing product_attribute based on the conditions supplied in where(...) if found. If not found, we build a new product_attribute with line_item.build_product_attribute.

Related

Rails trying to save form with collection_select that is empty gives undefined method `map' for nil:NilClass

I have a form with a drop down generated from a collection_select. The collection_select starts off blank and then when the user selects a date from the date field, the collection_select is updated with values for the date that is chosen.
I'm trying to show a nice error message if the form is submitted without a value chosen in my dropdown. Currently i'm getting this error: undefined methodmap' for nil:NilClass`
How can i make it so that if the user doesn't select a value in the dropdown, I can show them a nice error message?
View
<%= form_for(#arrangement) do |f| %>
<div class="control-group">
<%= f.label :date, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :date, :class => 'input-large datepicker' %>
</div>
</div>
<div class="control-group">
<%= f.label :timeslot, :class => 'control-label' %>
<div class="controls">
<%= collection_select(:arrangement, :timeslot_id, #available_timeslots, :id, :timeslot_spelled) %>
</div>
</div>
<% end %>
Controller
# GET /arrangements/new
# GET /arrangements/new.json
def new
date = Time.now.to_date.to_s(:db)
#arrangement = Arrangement.new
#available_timeslots = Timeslot.where("location_id = ? AND date(timeslot) = ? AND arrangement_id is null", current_user.user_details.location_id, date).order('timeslot ASC')
respond_to do |format|
format.html # new.html.erb
format.json { render json: #arrangement }
end
end
# POST /arrangements
# POST /arrangements.json
def create
#arrangement = Arrangement.new(params[:arrangement])
respond_to do |format|
if #arrangement.save
# update the timslot record with the arrangement id
if #timeslot = Timeslot.update(#arrangement.timeslot_id, :arrangement_id => #arrangement.id)
format.html { redirect_to #arrangement, notice: 'Arrangement was successfully created.' }
format.json { render json: #arrangement, status: :created, location: #arrangement }
else
format.html { render action: "new" }
format.json { render json: #arrangement.errors, status: :unprocessable_entity }
end
else
format.html { render action: "new" }
format.json { render json: #arrangement.errors, status: :unprocessable_entity }
end
end
end
The error given is referring to #available_timeslots being empty when trying to save the form
I would try something like this.
def new
#available_timeslots = ...
if #available_timeslots.count > 0
flash.now[:error] = "nil errrraaarrr"
end
...
end
In view
<div class="controls">
<%- if #available_timeslots.count > 0 %>
<%= collection_select(:arrangement, :timeslot_id, #available_timeslots, :id, :timeslot_spelled) %>
<% else %>
<%= flash.now[:error] %>
<% end %>
</div>
#available_timeslots is nil. Make sure it's set with an array of available timeslots to avoid this error message.
The trick was to add #available_timeslots = [] in the else clause
def create
#arrangement = Arrangement.new(params[:arrangement])
respond_to do |format|
if #arrangement.save
# update the timslot record with the arrangement id
if #timeslot = Timeslot.update(#arrangement.timeslot_id, :arrangement_id => #arrangement.id)
format.html { redirect_to #arrangement, notice: 'Arrangement was successfully created.' }
format.json { render json: #arrangement, status: :created, location: #arrangement }
else
format.html { render action: "new" }
format.json { render json: #arrangement.errors, status: :unprocessable_entity }
end
else
format.html { render action: "new" }
format.json { render json: #arrangement.errors, status: :unprocessable_entity }
end
end
end

Assigning multiple associations with Simple_form

I understand how to implement a single has_many association using simple_form, but how do you assign an additional association from another model object?
In my code, I'm creating model object #opportunity. I'm currently assigning a company_id, but also need to assign a 'user_id.
#opportunity _form.html.erb
<% if user_signed_in? %>
<%= simple_form_for([#company, #company.opportunities.build], html: {class: "form-inline"}) do |f| %>
<%= f.error_notification %>
<%= f.input :description, label: false, placeholder: 'Create an opportunity', input_html: { class: "span4" } %>
<%= f.submit 'Submit', class: 'btn btn-small'%>
<% end %>
<% else %>
<%= link_to "Create an Account", new_user_registration_path %>
to contribute
<% end %>
opportunity_controller.rb
def create
#company = Company.find(params[:company_id])
#opportunity = #company.opportunities.create(params[:opportunity])
respond_to do |format|
if #opportunity.save
format.html { redirect_to company_path(#company), notice: 'Opportunity was successfully created.' }
format.json { render json: #opportunity, status: :created, location: #opportunity }
else
format.html { render action: "new" }
format.json { render json: #opportunity.errors, status: :unprocessable_entity }
end
end
end
Assuming that your user is logged in, you can change your controller action to the following:
def create
#company = Company.find(params[:company_id])
#opportunity = #company.opportunities.new(params[:opportunity]) # new instead of create
#opportunity.user = current_user # new
respond_to do |format|
if #opportunity.save
format.html { redirect_to company_path(#company), notice: 'Opportunity was successfully created.' }
format.json { render json: #opportunity, status: :created, location: #opportunity }
else
format.html { render action: "new" }
format.json { render json: #opportunity.errors, status: :unprocessable_entity }
end
end
end

Rails create form for model with many to many relation

I have two models, Recipe and Tag, with a has_and_belongs_to_many relation. For this relation I have a simple join table, RecipesTags.
Recipe:
has_and_belongs_to_many :tags
Tag:
has_and_belongs_to_many :recipes
Now upon creating a new recipe, the user gets to fill in which category the recipe belongs to in forms of checkboxes, like "Meat", "Fish", and so on. These categories are in fact just tags in the database.
Problem: the recipes doesn't get any tags saved to it.
Recipe new and create controller methods:
def new
#recipe = Recipe.new
#ingredients = Ingredient.all
#tags = Tag.all
respond_to do |format|
format.html # new.html.erb
format.json { render json: #recipe }
end
end
# POST /recipes
# POST /recipes.json
def create
#recipe = Recipe.new(params[:recipe])
if (params[:tags])
#recipe.tags << params[:tags]
end
respond_to do |format|
if #recipe.save
format.html { redirect_to #recipe, notice: 'Recipe was successfully created.' }
format.json { render json: #recipe, status: :created, location: #recipe }
else
format.html { render action: "new" }
format.json { render json: #recipe.errors, status: :unprocessable_entity }
end
end
end
The view:
<%= form_for(#recipe, :html => {:multipart => true}) do |f| %>
<% if #recipe.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#recipe.errors.count, "error") %> prohibited this recipe from being saved:</h2>
# [ fields that get's saved for the recipe and works fine ]
<% #tags.each do |t| %>
<%= f.label t.name %>
<%= f.check_box :tags, t.name %>
<br />
<% end %>
<%= f.submit 'Submit recipe', :class => 'btn btn-primary' %>
<% end %>
At the moment, I get an error message saying:
undefined method `merge' for "Meat":String
"Meat" is the tag name.
So, what am I doing wrong here?
I think the issue is this line #recipe.tags << params[:tags].
The association method you're calling with << takes an object (in this case expecting a tag object), but in this case it seems you might be passing it a string.
For more info this link may be helpful http://guides.rubyonrails.org/association_basics.html#has_and_belongs_to_many-association-reference, in particular where it refers to collection<<(object, …).
In your controller you'll want to do something like #recipe.tags << tag where tag is a specific tag object.
So, try this:
In your controller
params[:tags].each do |k,v|
#recipe.tags << Tag.find(k)
end
In your view
<% #tags.each do |t| %>
<%= f.label t.name %>
<%= f.check_box "tags[#{t.id}]" %>
<br />
<% end %>
Try this:
def create
#recipe = Recipe.new(params[:recipe])
params[:tags].each do |tag|
#recipe.tags << Tag.find_by_name(tag)
end
respond_to do |format|
if #recipe.save
format.html { redirect_to #recipe, notice: 'Recipe was successfully created.' }
format.json { render json: #recipe, status: :created, location: #recipe }
else
format.html { render action: "new" }
format.json { render json: #recipe.errors, status: :unprocessable_entity }
end
end
end
In view:
<% #tags.each do |t| %>
<%= label_tag t.name %>
<%= check_box_tag "tags[#{t.name}]", t.name %>
<br />
<% end %>

redirect using a form

this form (views/workers/_form.html.erb) redirects me to the index of tasksadmins, after I push the 'create tasksadmin' button.
I want it to redirect me to "workers/index" and change the button to 'update the task'.
how can I do that please?
<%= form_for(#tasksadmin) do |f| %>
<% if #tasksadmin.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#tasksadmin.errors.count, "error") %> prohibited this tasksadmin from being saved:</h2>
<ul>
<% #tasksadmin.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.hidden_field :admin_mail, :value => #tasksadmin.admin_mail %>
<%= f.hidden_field :worker_mail, :value => #worker_mail %>
<%= f.hidden_field :task, :value => #tasksadmin.task %>
<div class="field">
<%= f.label :done %><br />
<%= f.check_box :done %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
and this is my workers_controller:
class WorkersController < ApplicationController
# GET /workers
# GET /workers.json
def index
#tasks_worker = Tasksadmin.where(:worker_mail => "alon.shmiel#gmail.com")
respond_to do |format|
format.html # index.html.erb
format.json { render json: #workers }
end
end
# GET /workers/1
# GET /workers/1.json
def show
#task_worker = Tasksadmin.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #worker }
end
end
# GET /workers/new
# GET /workers/new.json
def new
#worker = Worker.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #worker }
end
end
# GET /workers/1/edit
def edit
#tasksadmin = Tasksadmin.find(params[:id])
#worker_mail = "alon.shmiel#gmail.com"
end
# POST /workers
# POST /workers.json
def create
#worker = Worker.new(params[:worker])
respond_to do |format|
if #worker.save
format.html { redirect_to "#worker", notice: 'Worker was successfully created.' }
format.json { render json: #worker, status: :created, location: #worker }
else
format.html { render action: "new" }
format.json { render json: #worker.errors, status: :unprocessable_entity }
end
end
end
# PUT /workers/1
# PUT /workers/1.json
def update
#worker = Tasksadmin.find(params[:id])
respond_to do |format|
if #worker.update_attributes(params[:worker])
format.html { render action: "index", notice: 'Worker was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #worker.errors, status: :unprocessable_entity }
end
end
end
# DELETE /workers/1
# DELETE /workers/1.json
def destroy
#worker = Tasksadmin.find(params[:id])
#worker.destroy
respond_to do |format|
format.html { render action: "index" }
format.json { render json: #worker }
end
end
end
In your controller, you have to redirect to the appropriate path like so:
def update
redirect_to "workers/index"
end
I would suggest using path helpers so if you have your routes set up as resources, you can do this:
redirect_to workers_path
As for changing the the button text, just change it to:
f.submit("update the task")
You create a form for an object #tasksadmin, which in your WorkersController#edit is set as follows:
#tasksadmin = Tasksadmin.find(params[:id]
This means that that parameter contains an object of class Tasksadmin, if you let rails build the path for the a Tasksadmin, it will send you to the TasksadminsController#update, and that is why your code does not work. You never get to the WorkersController#update. Check your logs to verify that.
Let me be very clear about this: you should not edit Tasksadmin objects in the WorkersController.
I do not understand why you would do that.

Rails: ActiveRecord::RecordNotFound in AlbumsController#create Couldn't find User without an ID

Hi I'm currently receiving an error in my controller on submitting a form for creating an album. This is my first project and I am pretty shaky on controllers and what params to put and what to set the instance variables as... please help!!
on submission of my new.html.erb form, I receive
ActiveRecord::RecordNotFound in AlbumsController#create
Couldn't find User without an ID
here is my albums_controller
class AlbumsController < ApplicationController
def index
#albums = Albums.all
respond_to do |format|
format.html
format.json { render json: #albums }
end
end
def show
#albums = Album.all
#album = Album.find(params[:id])
#photo = Photo.new
end
def update
end
def edit
end
def create
#user = User.find(params[:user_id])
#user.album = Album.new(params[:album])
respond_to do |format|
if #user.album.save
format.html { redirect_to #user, notice: 'Album was successfully created.' }
format.json { render json: #album, status: :created, location: #album}
else
format.html { render action: "new" }
format.json { render json: #album.errors, status: :unprocessable_entity }
end
end
end
def new
#user = User.find(params[:user_id])
#album = Album.new
end
def destroy
end
end
here is the form I'm submitting
<%= form_for (#album), :html => { :id => "uploadform", :multipart => true } do |f| %>
<div>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :description %>
<%= f.text_area :description %>
<br>
<%=f.submit %>
Let me know if you need any more files.
In your createmethod you're trying to fetch a user from the database, based on params[:user_id], and params doesn't contain any user_id.
In this case I believe that it should come from the URL
So one solution if an album belongs to the user would be to set your routes like that :
resources :users do
resources :albums
end
Then you'll have to tell your form that the album is nested under a user byt explicitly giving the url. user_albums_path matches /users/:user_id/albums(.:format)
<%= form_for (#album), url: user_albums_path :html => { :id => "uploadform", :multipart => true } do |f| %>
<div>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :description %>
<%= f.text_area :description %>
<br>
<%=f.submit %>
The your create method you receive the user_id it need in the params.
Let me know if'm not clear enough or if you need more explanations
You should use the build method defined here
#user = User.find(params[:user_id])
#user.album = Album.new(params[:album])
to create the album, you should
#user = User.find(params[:user_id])
#user.albums.build params[:album])
this will automatically set the user_id attribute of the album to #user.id, you won't have anything to do
so your create method should be
def create
#user = User.find(params[:user_id])
#album = #user.albums.build params[:album]
respond_to do |format|
if #album.save
format.html { redirect_to user_path(#user), notice: 'Album was successfully created.' }
format.json { render json: #album, status: :created, location: #album} # I don't know what this location is
else
format.html { render action: "new" }
format.json { render json: #album.errors, status: :unprocessable_entity }
end
end
end

Resources