when I submit the form :
Parameters: {"authenticity_token"=>"LJ/ZME2lHZ7VwCDgPKX6OFe326fXSXo5UB4M0cPwbCE=", "project_id"=>"second", "utf8"=>"✓", "commit"=>"Add Todo", "esthour"=>{"rfp_id"=>"2", "cms_est_hours"=>"", "modul1hours_attributes"=>{"0"=>{"module_est_hours"=>"11", "modul1_id"=>"3"}, "1"=>{"module_est_hours"=>"111", "modul1_id"=>"4"}}, "designpages_est_hours"=>"", "ecommerce_est_hours"=>""}}
models
class Esthour < ActiveRecord::Base
has_many :modul1hours
accepts_nested_attributes_for :modul1hours
end
class Modul1hour < ActiveRecord::Base
belongs_to :esthour
attr_accessible :module_est_hours,:module_act_hours,:modul1_id,:esthour_id
end
view
<% #m1.map(&:id).each do |id|%>
<%= b.fields_for :modul1hours, #esthour.modul1hours.build do |f| %>
<%= f.hidden_field :modul1_id, :value => id %>
<%= f.text_field :module_est_hours, :size => 30 %>
</tr>
<% end %>
<% end %>
controller
def new
#esthour = Esthour.new
#project = params[:project_id]
respond_to do |format|
format.html # new.html.erb
format.json { render :json => #esthour }
end
end
You can see my earlier question regarding this.
I'm waiting for valuable reply. Thanks.
you should add in your Esthour model:
attr_accessible :modul1hours_attributes
Related
I have two controllers - ItemsController and TradesController. I'm building a #trade inside the ItemsController #show action, which is sent to the TradesController #create action with a form.
class ItemsController < ApplicationController
def show
#item = Item.friendly.find(params[:id])
#trade = current_user.requested_trades.build
#approved_trades = #item.trades
respond_to do |format|
format.html
format.json { render :json => #items.to_json(:methods => [:image_url]) }
end
end
class TradesController < ApplicationController
def create
#trade = current_user.requested_trades.build(trade_params)
respond_to do |format|
if #trade.save
format.html { redirect_to #trade, notice: "Your request for trade has been submitted. You will be notified once it is approved or denied." }
format.json { render :index, status: :created, location: #trade }
else
format.html { redirect_to #trade, notice: "Pick another amount" }
end
end
end
private
def trade_params
params.require(:trade).permit(:trade_requester, :trade_recipient, :wanted_item, :collateral_item, :shares)
end
end
And then here's my Trade model
class Trade < ActiveRecord::Base
belongs_to :trade_requester, class_name: "User"
belongs_to :trade_recipient, class_name: "User"
belongs_to :wanted_item, class_name: "Item"
belongs_to :collateral_item, class_name: "Item"
end
Here's the form in my Item's show view:
<%= form_for(#trade) do |f| %>
<%= f.hidden_field :wanted_item, value: #item.id %>
<div class="field">
<%= f.text_field :shares, placeholder: "Pick a number between 1 and #{#item.shares}" %>
<%= f.submit "Trade", class: "button minty-button wide-button" %>
</div>
<% end %>
The above code for the ItemsController posts to the TradesController create action, but I'm getting an error that says ActiveRecord::AssociationTypeMismatch in TradesController#createItem(#70095717466760) expected, got String(#70095657672800)
Why is that expecting an Item? It seems that if #trade creation results in error, then it should redirect to #trade.
The quick solution is to change your hidden field from :wanted_item to :wanted_item_id:
<%= form_for(#trade) do |f| %>
<%= f.hidden_field :wanted_item_id, value: #item.id %>
<div class="field">
<%= f.text_field :shares, placeholder: "Pick a number between 1 and #{#item.shares}" %>
<%= f.submit "Trade", class: "button minty-button wide-button" %>
</div>
<% end %>
Also, make sure your trade_params method permits wanted_item_id:
def trade_params
params.require(:trade).permit(:trade_requester, :trade_recipient, :wanted_item_id, :collateral_item_id, :shares)
end
You may have a similar issue with :collateral_item in another form.
I am a noob on Ror. Been looking for my problem answers for 3 days now, I have been looking for the answers but can’t find one with my specific problem. ( I even found it hard to write the right title)
So I have been trying to build a nested form in RoR. I have a simple order form that enable users to specify the quantity they ordered in that form. The form will only store the value into the database if the quantity text field is not empty.
The Order form is simply look like this:
I am storing the quantity data into the join table between order and inventory which has many to many relationship through Inventory_orders table. now in the Inventory_orders table instead of only having orders_id and inventories_id , I also add the quantity column.
now I have been able to get the form working with the code below:
Controller:
def new
#order = Order.new
#customer = Customer.all
#inventories_list = Inventory.all
#inventory_order = #order.inventory_orders.build
end
def create
#order = Order.new(order_params)
#inventories_list = Inventory.all #controller can call any model
respond_to do |format|
if #order.save
format.html { redirect_to #order, notice: 'Order was successfully created.' }
format.json { render :show, status: :created, location: #order }
else
format.html { render :new }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
def order_params
params.require(:order).permit(:customer_id, :order_ids => [],:inventory_orders_attributes => [:id, :quantity, :inventory_id ])
end
View:
<%= form_for(#order) do |f| %>
<div id = “Main_Container">
*** Some Code ***
<table id = "inventory_table">
<tr>
<td class = "prodCodeTitle"><h3>Prod Code</h3></td>
<td class = "prodResult"><h3>Quantity</h3></td>
<td class = "prodResult"><h3>Size</h3></td>
<td class = "prodResult"><h3>Price</h3></td>
</tr>
//Here display all the inventories list
<% #inventories_list.each do |t| %>
<tr>
<td class ="prodResult"><%= link_to t.pName, inventory_path(t), :remote => true %></td>
<td class = “prodResult">
//nested form for the join table
<%= f.fields_for :inventory_orders do |qty| %>
<%= qty.hidden_field :inventory_id , value: t.id %>
<%= qty.number_field :quantity %>
<%end%>
</td>
<td class = "prodResult"><%= t.pMeter %></td>
<td class = "prodResult"><%= t.pSellPrice %></td>
</tr>
<% end %>
*** Some Code***
<% end %>
Model:
class Order < ActiveRecord::Base
belongs_to :customer
has_many :inventory_orders
has_many :inventories, through: :inventory_orders
validates :customer_id, :presence => true
accepts_nested_attributes_for :inventory_orders, :reject_if => lambda { |a| a[:quantity].blank?}
end
class InventoryOrder < ActiveRecord::Base
belongs_to :inventory
belongs_to :order
validates :quantity, :presence => true
end
Now when creating new Orders form , the application works and store the data that I want in the inventory_orders table.
The problem occurs when I try to edit the form. When trying to click on edit button I get this output in my View file:
for example this is what I Input into the form:
when I try to edit the form this is what I get:
this is my controller for edit:
def edit
#order = Order.find(params[:id])
#customer = Customer.all
#inventories_list = Inventory.all
end
I have been looking at the psql database schema by manual do sql query as follow:
select * from inventory_orders where inventory_orders.order_id = 63;
and get this as result:
now it seems that the fields_for Inventory_orders get the number of rows returned , but I don't get why all the quantity also get displayed 4 times for each product. Also how can I ensure that when I try to edit quantity for product “aaa” it will only display one number_field with what users has input before.
Sorry for the long post,otherwise I am not sure how to clearly convey my meaning.
EDITED
this to show my Inventory Model:
Class Inventory < ActiveRecord::Base
has_many :inventory_orders
has_many :orders, through: :inventory_orders
end
You need to use the following:
//Here display all the inventories list
<% #inventories_list.each do |t| %>
<%= link_to t.pName, inventory_path(t), :remote => true %>
<%= f.fields_for :inventory_orders, t do |qty| %>
<%= qty.hidden_field :inventory_id , value: t.id %>
<%= qty.number_field :quantity %>
<% end %>
<%= t.pMeter %>
<%= t.pSellPrice %
<% end %>
The issue is that since f.fields_for populates a form based on the built associated objects, if you're passing 4 fully constructed objects through the edit action, fields_for is going to populate all of them each time.
What you need is to use the instance of the associated data.
I think your code could be improved a lot:
#app/controllers/orders_controller.rb
class OrdersController < ApplicationController
def new
#order = Order.new
#inventory = Inventory.all
#inventory_order = #order.inventory_orders.build
end
def edit
#order = Order.find params[:id]
#inventory = Inventory.all
end
end
#app/views/orders/new.html.erb
<%= form_for #order do |f| %>
<% #inventory.each do |inventory| %>
<%= f.fields_for :inventory_orders, item do |item| %>
<%= item.text_field :quantity %>
<% end %>
<% end %>
<%= f.submit %>
<% end %>
#app/views/orders/edit.html.erb
<%= form_for #order do |f| %>
<%= f.fields_for #order.inventory_orders do |item| %>
<%= item.text_field :quantity %>
<% end %>
<%= f.submit %>
<% end %>
when I submit the form :
Parameters: {"authenticity_token"=>"LJ/ZME2lHZ7VwCDgPKX6OFe326fXSXo5UB4M0cPwbCE=", "project_id"=>"second", "utf8"=>"✓", "commit"=>"Add Todo", "esthour"=>{"rfp_id"=>"2", "cms_est_hours"=>"", "modul1hours_attributes"=>{"0"=>{"module_est_hours"=>"11", "modul1_id"=>"3"}, "1"=>{"module_est_hours"=>"111", "modul1_id"=>"4"}}, "designpages_est_hours"=>"", "ecommerce_est_hours"=>""}}
models
class Esthour < ActiveRecord::Base
has_many :modul1hours
accepts_nested_attributes_for :modul1hours
end
class Modul1hour < ActiveRecord::Base
belongs_to :esthour
attr_accessible :module_est_hours,:module_act_hours,:modul1_id,:esthour_id
end
view
<% #m1.map(&:id).each do |id|%>
<%= b.fields_for :modul1hours, #esthour.modul1hours.build do |f| %>
<%= f.hidden_field :modul1_id, :value => id %>
<%= f.text_field :module_est_hours, :size => 30 %>
</tr>
<% end %>
<% end %>
controller
def new
#esthour = Esthour.new
#project = params[:project_id]
respond_to do |format|
format.html # new.html.erb
format.json { render :json => #esthour }
end
end
You can see my earlier question regarding this.
I'm waiting for valuable reply. Thanks.
I think I have a working version of acts_as_commenting_with_threading in my rails app, but it seems like the body of every comment is saved with weird formatting. How do I remove the formatting in my view so it only displays the text (and not the formatting)? For example, if I type the text "test comment," the body of the comment is saved as "---\nbody: test comment\n". I tried html_safe, but it didn't work.
step.rb
class Step < ActiveRecord::Base
extend FriendlyId
acts_as_commentable
friendly_id :position
has_ancestry :orphan_strategy => :adopt
attr_accessible :description, :name, :position, :project_id, :images_attributes, :parent_id, :ancestry, :published_on
belongs_to :project
has_many :images, :dependent => :destroy
accepts_nested_attributes_for :images, :allow_destroy => :true
validates :name, :presence => true
end
comments_controller.rb
class CommentsController < ApplicationController
def create
#project = Project.find(params[:project_id])
#commentText = params[:comment]
#user = current_user
#comment = Comment.build_from(#project.steps.find(params[:step_id]), #user.id, #commentText)
respond_to do |format|
if #comment.save
format.html {redirect_to :back}
else
format.html { render :action => 'new' }
end
end
end
end
show.html.erb:
<div class="stepComments">
<% if step.comment_threads.count >0 %>
<% step.comment_threads.each do |stepComment| %>
<% if stepComment.body.length>0 %>
<%= render :partial => 'comments', :locals => {:comment=> stepComment} %>
<% end %>
<br>
<% end %>
<% end %>
</div>
_comments.html.erb
<div class="comment">
<div class="userIcon">
<%= User.find(comment.user_id).username %>
<%= image_tag(User.where(:id=>comment.user_id).first.avatar_url(:thumb), :class=>"commentAvatar img-polaroid")%>
</div>
<div class="field">
<%= comment.body %>
</div>
</div>
This prints: "---\nbody: test comment\n"
The rails helper simple_format will print using the formatting rules so you will get just the text.
For example, <% simple_format(comment.body) %>
I couldn't figure out a way to do it besides just edited the string manually. This is what I ended up using:
<%= comment.body.slice((comment.body.index(' ')+1..comment.body.length)) %>
It seems very odd that there isn't some built in function for doing this...
It ended up being a quite simple solution; I had been calling the parameter incorrectly. It should have been:
#commentText = params[:comment][:body]
I have a nested form based in a has_one relationship but it's not showing the fields.
What am I missing?
New action
def new
#doctor = Doctor.new
1.times { #doctor.build_schedule }
respond_to do |format|
format.html # new.html.erb
format.json { render json: #doctor }
end
end
_form
<%= simple_form_for(#doctor, :html => { class: "form-horizontal"}) do |f| %>
<%= f.input :name %>
<%= f.simple_fields_for :schedule do |builder| %>
<%= render 'days_checkboxes', :f => builder %>
<%= f.submit %>
<% end %>
Model
class Doctor < ActiveRecord::Base
has_one :schedule, dependent: :destroy
end
Do I have to set the build in other actions?
If there is no schedule associated object on your model instance, yes you will need to call build_schedule wherever you want to reference it. If you didn't do this, the form wouldn't render at all because it has nothing to display the fields for.