I have two models,
class ProcessType < ActiveRecord::Base
has_many :remarks
validates :code, :name, presence: true
end
class Remark < ActiveRecord::Base
belongs_to :process_type
belongs_to :origin
validates :description, presence: true
end
The foreign key is set correctly, the remarks table has a process_type_id column.
On the Create form, I display the processes available using a select:
<%= simple_form_for #remark do |f| %>
<%= collection_select(:remark, :process_type_id, ProcessType.all, :id, :name) %>
<%= f.input :description, label: 'Description' %>
<%= f.input :suggestion, label: 'Suggestion' %>
<%= f.button :submit %>
<% end %>
My problem is that in the remarks table, after saving, the id of the process is always null. What am I missing? Is probably something obvious, but I am not able to see it right now.
Thanks!
Try this:
<%= f.collection_select :process_type_id, ProcessType.all, :id, :name %>
or, if you want to use the Simple Form methods:
<%= f.input :process_type_id, :collection => ProcessType.all %>
Related
I'm currently doing this
class User < ApplicationRecord
has_many :courses, dependent: :destroy
end
class Course < ApplicationRecord
belongs_to :user
def title_with_username
"#{title} by #{user.username}"
end
end
<%= simple_form_for #tag do |f| %>
<%= f.input :category_id, collection: Category.all %>
<%= f.input :course_id, collection: Course.all, label_method: :title_with_username, value_method: :id %>
<%= f.button :submit %>
<% end %>
Is it possible to do the label_method all in the view without touching the model?
You can convert your existing select tag to something like
<%= f.input :course_id, collection: Course.all.map {|c| [c.id, "#{c.title} by #{c.user.username}"]} %>
You can build this collection array in controller and pass here as views should not be unnecessarily cluttered.
I don't fully understand why but this seems to work
<%= f.input :course_id, collection: Course.all, label_method: lambda { |course| "#{course.title} by #{course.user.username}" }, value_method: :id %>
I'm running Rails 6.0.0.rc1 and having trouble getting a triple nested form working. I have products that have options that have option_values. So a Product might have an option called "Color" and an Option Value named "Red." I'd like to create all of these in a classic nested form in the Product form.
The form works and I can save Product with an Option, but not the Option Value on submit. I'm not sure why it's not working when I try to embed fields_for Option Values inside the fields_for Options.
What am I doing wrong here? I feel like I'm missing something obvious, but can't figure it out. (Probably not relevant, but note that I need to scope each object to account_id and my User has_one :account that's the reason for the hidden field.)
Here is my product model:
class Product < ApplicationRecord
belongs_to :account
has_many :options, dependent: :destroy
accepts_nested_attributes_for :options, allow_destroy: true
validates :account_id, presence: true
validates :name, presence: true
end
Option model:
class Option < ApplicationRecord
belongs_to :account
belongs_to :product
has_many :option_values, dependent: :destroy
accepts_nested_attributes_for :option_values, allow_destroy: true
validates :account_id, presence: true
validates :name, presence: true
end
OptionValue model:
class OptionValue < ApplicationRecord
belongs_to :account
belongs_to :option
validates :account_id, presence: true
validates :name, presence: true
end
Here's the Product form:
<%= form_with(model: product, local: true) do |f| %>
<%= f.fields_for :options do |options_form| %>
<fieldset class='form-group'>
<%= options_form.hidden_field :account_id, value: current_user.account.id %>
<%= options_form.label :name, 'Option' %>
<%= options_form.text_field :name, class: 'form-control' %>
</fieldset>
<%= f.fields_for :option_values do |values_form| %>
<fieldset class='form-group'>
<%= values_form.label :name, 'Value' %>
<%= values_form.text_field :name, class: 'form-control' %>
</fieldset>
<% end %>
<% end %>
<% end %>
ProductsController:
class ProductsController < ApplicationController
def new
#product = Product.new
#product.options.build
end
def create
#account = current_user.account
#product = #account.products.build(product_params)
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
else
format.html { render :new }
end
end
end
private
def product_params
params.require(:product).permit(
:account_id, :name,
options_attributes: [
:id, :account_id, :name, :_destroy,
option_values_attributes:[:id, :account_id, :name, :_destroy ]
]
)
end
end
At first, you need to change the form to nest option_values inside option, and add account_id field to option values:
<%= form_with(model: product, local: true) do |f| %>
<%= f.fields_for :options do |options_form| %>
<fieldset class='form-group'>
<%= options_form.hidden_field :account_id, value: current_user.account.id %>
<%= options_form.label :name, 'Option' %>
<%= options_form.text_field :name, class: 'form-control' %>
</fieldset>
<%= options_form.fields_for :option_values do |values_form| %>
<fieldset class='form-group'>
<%= values_form.hidden_field :account_id, value: current_user.account.id %>
<%= values_form.label :name, 'Value' %>
<%= values_form.text_field :name, class: 'form-control' %>
</fieldset>
<% end %>
<% end %>
<% end %>
Also you need to build nested records in the controller. Another option is to build them dynamically via javascript (look at the cocoon gem, for example). To build 3 options with 3 values each:
def new
#account = current_user.account
# it is better to create associated product
#product = #account.products.new
3.times do
option = #product.options.build
3.times { option.option_values.build }
end
end
Update:
Because I was trying to follow along this Nested Form Railscast, the biggest problem was that I didn't realize that the version Ryan Bates has working is on "Edit", not "New", so I added the Products, Options, and Values via the console and got the form working with this code:
_form.html.erb
<%= f.fields_for :options do |builder| %>
<%= render 'option_fields', f: builder %>
<% end %>
_option_fields.html.erb
<fieldset class='form-group'>
<%= f.hidden_field :account_id, value: current_user.account.id %>
<%= f.label :name, 'Option' %>
<%= f.text_field :name, class: 'form-control' %>
<br>
<%= f.check_box :_destroy, class: 'form-check-input' %>
<%= f.label :_destroy, 'Remove Option' %>
<small id="optionHelp" class="form-text text-muted">
(e.g. "Size" or "Color")
</small>
<%= f.fields_for :option_values do |builder| %>
<%= render 'option_value_fields', f: builder %>
<% end %>
</fieldset>
_option_value_fields.html.erb
<fieldset class='form-group'>
<%= f.hidden_field :account_id, value: current_user.account.id %>
<%= f.label :name, 'Value' %>
<%= f.text_field :name, class: 'form-control' %>
<br>
<%= f.check_box :_destroy, class: 'form-check-input' %>
<%= f.label :_destroy, 'Remove Value' %>
<small id="optionValueHelp" class="form-text text-muted">
(e.g. "Small, Medium, Large" or "Red, Green, Blue")
</small>
</fieldset>
Also, the only difference with the Railscast is using strong parameters in the controller, so you'll just need to nest them like this:
ProductsController
def product_params
params.require(:product).permit(:account_id, :name, options_attributes [:id, :account_id, :name, :_destroy, option_values_attributes: [:id, :account_id, :name, :_destroy]])
end
OptionsController
def option_params
params.require(:option).permit(:account_id, :name, option_values_attributes [:id, :account_id, :name, :_destroy])
end
OptionValuesController
def option_value_params
params.require(:option_value).permit(:account_id, :option_id, :name)
end
Rather than building the nested objects in the controller I'm going to do it with Javascript as in the Railscast episode or with the Cocoon gem as Vasilisa suggested in her answer.
Just wanted to share the code that actually ended up working in case someone else runs into similar problems. I think the Railscast, though old, is still a great introduction to nested forms in Rails, but you just have to be aware of the changes required to use form_with and strong parameters. Big thanks to Vasilisa for helping me figure this out.
The main "gotchas" that you need to look out for when following the Rails Nested Form Railscast are this:
form_with has some different syntax than the older rails form_tag
Make sure you don't have any typos or name problems when creating your form blocks because these are nested twice
Same with nesting parameters in your controllers, just be aware of your syntax and typos
Be aware that Ryan Bates is demoing with data that wasn't added through the form he's building so if you'd like to follow along you'll need to create some data in the console
With strong parameters you'll have to explicitly list :_destroy as a parameter in order for his "Remove" checkboxes to work
Hello people I have some challenges here with devise authentication for users:
I have two models called color and sub_color in my application. the sub_color belongs_to color and color has_many sub_colors.I have already seeded the database with the appropriate data
The challenge; I want a user to be able to chose these in the devise form_for when they are registering as a collection object and the id of the sub_color will be used for identifying a particular user also(a situation where for instance I can sort all the users which cosed blue color). How do I achieve this please?
This is what I have tried but it is not working:
%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :email, required: true, autofocus: true %>
<%= f.input :user_name, required: true %>
<%= f.input :password, required: true, hint: ("# {#minimum_password_length} characters minimum" if #minimum_password_length) %>
<%= f.input :password_confirmation, required: true %>
<%= f.input :first_name, required: true %>
<%= f.label :color_id, "Color" %> <br/>
<%= f.collection_select :color_id, Color.order(:name), :id, :name, include_blank: true%>
<%= f.label :sub_color_id, "Sub Color" %> <br/>
<%= f.grouped_collection_select :sub_color_id, Color.order(:name), :sub_color, :name, :id, :name, include_blank: true%>
<div class="form-actions">
<%= f.button :submit, "Sign up" %>
</div>
model for users:
belongs_to :sub_color
has_one :color, through: :sub_color
devise.......
end
model for sub_color
has_many :users
belongs_to :color
end
model for color
has_many :sub_color
end
This is the error I see on the web browser
NoMethodError in Devise::Registrations#new
[undefined method `color_id' for #<User:0xbacc720>]
Firstly, You need to add color_id and sub_color_id to users table.
Then define association, in user.rb belongs_to :sub_color and in sub_color.rb has_many :users. Same goes with color, user.rb belongs_to :color and in color.rb has_many :users .
Hope that helps!
I'm trying to manage invitations to an event with a "participation" model. I'd like that, when I invite a user, i could insert his name in the form, instead of user_id.
user.rb
class User < ActiveRecord::Base
attr_accessible :id, :name
has_many :participations
end
participation.rb
class Participation < ActiveRecord::Base
attr_accessible :event_id, :user_id
belongs_to :event
belongs_to :user
end
views/participations/new.html.erb
<%= form_for(#participation) do |f| %>
<%= f.hidden_field :event_id, value: #event.id %>
<%= f.label :user_id, 'User Id' %>
<%= f.number_field :user_id %>
<%= f.submit 'Invite' %>
<% end %>
How can i do?
Try by this:
<%= form_for(#participation) do |f| %>
<%= f.hidden_field :event_id, value: #event.id %>
<%= f.label :user_id, 'User Id' %>
<%=f.collection_select :user_id,User.all,:id,:name,:label => "User" ,:include_blank => false%>
<%= f.submit 'Invite' %>
<% end %>
You may turn include_blank to true or false as you wish to always have a user or not.
Feel free to ask for more if this doesn't solve your problem.
Here's my user model:
class User < ActiveRecord::Base
has_one :teacher, :dependent => :destroy
accepts_nested_attributes_for :teacher, :allow_destroy => true
attr_accessible :email, :password, :password_confirmation, :remember_me, :teacher_attributes
end
Here's my teacher model:
class Teacher < ActiveRecord::Base
belongs_to :user
attr_accessible :user_id, :first_name, :last_name
validates_presence_of :user_id, :first_name, :last_name
end
Here's my form:
<%= form_for(#user, :url => registration_path(:user)) do |user| %>
<%= user.text_field :email %>
<%= user.text_field :password %>
<%= user.text_field :password_confirmation %>
<%= user.fields_for resource.build_teacher do |t| %>
<%= t.text_field :first_name %>
<%= t.text_field :last_name %>
<%= t.text_field :phone %>
<% end %>
<%= user.submit 'Confirm' %>
<% end %>
Except that this thing won't "accept nested attributes"
My development log says:
WARNING: Can't mass-assign protected attributes: teacher
I don't know if it's related, but the form isn't generating fields inside a teacher_attributes array or anything - it's inside teacher. I'm guessing that's where my problem is, but I don't how to make it put the fields inside it. Please help.
Thanks!
Try these things:
At top of view:
<% #user.build_teacher if #user.teacher.nil? %>
For the fields for:
<%= user.fields_for :teacher do |t| %>
Also, personally, I like naming the block parameters in forms (the part |user| and |t|) as |form| (because when you're having a long day, and you see user down in the view and not form, it can confuse you!)