I have this form in rails, in my view new.html.erb
<%= form_for( #rent , html: { class: 'form-horizontal' }) do |f| %>
<div class="form-group">
<label for="" class="col-lg-2 col-md-3 col-sm-3 col-xs-3 control-label">year:</label>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<%= f.text_field :year, class: 'form-control' %>
</div>
<div class="col-lg-2 col-md-3 col-sm-3 col-xs-3">
<%= f.submit 'Buscar', :class =>"btn btn-sm btn-info btn-flat" %>
</div>
<div class="clearfix"></div>
</div>
<% end %>
<%= render 'shared/error_messages', object: #rent %>
In my controller I have this
class RentsController < ApplicationController
def new
#rent = RentSearch.new
end
private
def search_params
params.require(:year).permit(:year)
end
end
In my model, had this code:
class RentSearch
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :year
validates :year, presence: true
validates :year, length: { is: 4 }
end
With this code I get this error
undefined method `persisted?' for #
But I made some modifications and not show error, but when submit not display any error and form is empty, I don't know how can solve this.
What is the best way to create a form in rails without model access to database and passing all validations to the controller and verify.
MY SOLUTION
Thanks to #Зелёный for help.
route.rb
resources :rents, only: [:index, :new, :create]
rent.rb - model
class Rent
# Validations
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :year
validates :year, presence: true
validates :year, length: { is: 4 }
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false # which means this object persisted in the database.
end
end
rents_controller.rb
class RentsController < ApplicationController
def index
#params = params
end
def new
#rent = Rent.new
end
def create
#rent = Rent.new( params['/rents'] )
if #rent.valid?
redirect_to tg_rents_path( year: params['/rents']['year'] )
else
render :action => 'new'
end
end
end
new.html.erb
<%= form_for( tg_rents_path , url: {action: "create"}, html: { class: 'form-horizontal' }) do |f| %>
<div class="form-group">
<label for="" class="col-lg-2 col-md-3 col-sm-3 col-xs-3 control-label">year:</label>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<%= f.text_field :year, class: 'form-control' %>
</div>
<div class="col-lg-2 col-md-3 col-sm-3 col-xs-3">
<%= f.submit 'Search', :class =>"btn btn-sm btn-info btn-flat" %>
</div>
<div class="clearfix"></div>
</div>
<% end %>
<%= render 'shared/error_messages', object: #rent %>
Thanks to all!!
Related
I have a parent table and in it there is a boolean field admin. I have a admin signup page where i want a hidden field for admin to set as true. Please help. I have tried the step below. please correct it as it is not working.
<div class='row'>
<div class= 'col-xs-12'>
<%= form_for(#parent, :html => { multipart: true, class: "form-horizontal", role: "form"}) do |f| %>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :email, class: "required" %>
</div>
<div class="col-sm-8">
<%= f.email_field :email, class: "form-control", placeholder: "Enter email", required: true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :password, class: "required" %>
</div>
<div class="col-sm-8">
<%= f.password_field :password, class: "form-control", placeholder: "Enter password", required: true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :password_confirmation, class: "required" %>
</div>
<div class="col-sm-8">
<%= f.password_field :password_confirmation, class: "form-control", placeholder: "Re-enter password", required: true %>
</div>
</div>
<%= f.hidden_field :admin, :value => true %>
<div class="form-group">
<div class="col-sm-10">
<%= f.submit 'Sign up', class: 'btn btn-primary btn-lg' %>
</div>
</div>
<% end %>
</div>
</div>
Parent controller
def addusers
#parent=Parent.new
end
Updated parent controller
def new
#parent = Parent.new
#parent.secondaryparents.build
add_breadcrumb "Home", :root_path
add_breadcrumb "Sign up"
end
def addusers
#parent=Parent.new
end
def create_users
#parent=Parent.new(parent_params)
#parent.admin = true
if #parent.save
ParentMailer.registration_confirmation(#parent).deliver
flash[:success] = "Please ask user to confirm email address to continue"
redirect_to main_admin_path
else
flash[:danger] = "There was an error with registering. Try again"
redirect_to main_admin_path
end
end
def create
#parent = Parent.new(parent_params)
if #parent.save
ParentMailer.registration_confirmation(#parent).deliver
flash[:success] = "Please confirm your email address to continue"
redirect_to root_path(#parent)
else
flash[:danger] = "There was an error with registering. Try again"
redirect_to signup_path
end
end
Routes
resources :parents do
resources :children do
resources :fundings
end
end
end
get 'signup', to:'parents#new'
get 'login', to: 'sessions#new'
get 'usersignup', to:'parents#addusers'
post 'usersignup', to:'parents#create_users'
resources :parents, except: [:new] do
member do
get :confirm_email
end
end
Remove hidden line from html page, no need it f.hidden_field :admin, :value => true
Form_for
form_for(#parent, url: usersignup_path,
:html => { multipart: true, class: "form-horizontal", role: "form"}) do |f|
Add to routes:
post 'usersignup', to:'parents#create_users'
Controller:
def create_users
#parent = Parent.new(parent_params)
#parent.admin = true
if #parent.save
#do yr logic here
else
redirect_back(fallback_location: "/", flash: { danger: "smth went wrong.." })
end
end
def parent_params
params.require(:parent).permit(:email, :password, :password_confirmation)
end
I am using carrierwave and trying to display images of products in the index view. This are my models, controllers and views
product.rb
class Product < ActiveRecord::Base
has_many :order_items
belongs_to :category, required: false
has_many :product_attachments
accepts_nested_attributes_for :product_attachments
mount_uploader :image, ImageUploader
default_scope { where(active: true) }
end
product_attachment.rb
class ProductAttachment < ApplicationRecord
mount_uploader :image, ImageUploader
belongs_to :product
end
products_controller.rb (extract)
class ProductsController < ApplicationController
def index
#products = Product.all
#order_item = current_order.order_items.new
end
def show
#product = Product.find(params[:id])
#product_attachments = #product.product_attachments.all
end
def new
#product = Product.new
#product_attachment = #product.product_attachments.build
#categories = Category.all.map{|c| [ c.name, c.id ] }
end
def create
#product = Product.new(product_params)
#product.category_id = params[:category_id]
respond_to do |format|
if #product.save
params[:product_attachments]['image'].each do |a|
#product_attachment = #product.product_attachments.create!(:image => a, :product_id => #product.id)
end
format.html { redirect_to #product, notice: 'Product was successfully created.' }
else
format.html { render action: 'new' }
end
end
end
private
def product_params
params.require(:product).permit(:name,:price, :active, :description, product_attachments_attributes:
[:id, :product_id, :image], category_attributes: [:category_id, :category])
end
end
index.html.erb
<div class="row">
<div class="col-xs-offset-1 ">
<% #products.each do |product| %>
<%= render "product_row", product: product, order_item: #order_item %>
<% end %>
</div>
_product_row.html.erb
<div class="well">
<div class="row">
<div class="container-fluid row">
<div class="col-md-5 col-lg-5 col-sm-5 col-xs-5 binder">
<br><%= image_tag product.image_url.to_s %><br><br>
</div>
<div class="col-md-4 col-lg-4 col-sm-4 col-xs-4 binder">
<h4 class="text-left"><%= product.name.split.map(&:capitalize).join(' ') %> </h4>
<h4 class="text-left"><span style="color: green"><%= number_to_currency(product.price, :unit => "€") %></span></h4>
<h4><%= link_to Category.find(product.category_id).name, category_path(product.category_id) %></h4>
<h6 class="text-left"><%= link_to 'Delete', product_path(product), method: :delete,
data: { confirm: 'Are you sure?' } %></h6><br><br>
</div>
<div class="col-md-3 col-lg-3 col-sm-3 col-xs-3 binder">
<%= form_for order_item, remote: true do |f| %>
<div class="input-group">
<%= f.number_field :quantity, value: 1, class: "form-control", min: 1 %>
<div class="input-group-btn">
<%= f.hidden_field :product_id, value: product.id %>
<%= f.submit "Add to Cart", class: "btn btn-primary text-right" %>
</div>
</div>
<% end %>
</div>
</div>
</div>
</div>
With <%= image_tag product.image_url.to_s %> the image doesn't appear. When I change it to <%= image_tag product_attachments.first.image_url.to_s %> I get the following error:
undefined local variable or method `product_attachments' for #<#<Class:0x00007f28544ccc68>:0x00007f285dd3aab8>
I am pretty new to Ruby and don't know what I am doing wrong or how to fix this. Any help would be appreciated. I am using Ruby version 2.5.1 and rails 5.2.0 on ubuntu.
I would expect that the following works:
<%= image_tag product.product_attachments.first.image_url.to_s %>
Try this:
image_tag(product.product_attachments.first.image.url.to_s)
It should work. I realized that sometimes image_url doesn't work as expected but image.url does.
If i understand well your snippets, the model you mount the ImageUploader is ProductAttachment (which have the attribute image) so you can remove mount_uploader :image, ImageUploader of your Product model.
The image is mounted on every product_attachments for one product. Just display the images inside the partial by iterating through product_attachments:
<% product.product_attachments.each do |attachment| %>
<%= image_tag(attachment.image.url) %>
<% end %>
I have two model:
1.Personne
class Personne < ApplicationRecord
has_one :proprietaire
accepts_nested_attributes_for :proprietaire
validates :nom, :prenom, :tel, :email,
presence: true
end
2 Proprietaire
class Proprietaire < ApplicationRecord
belongs_to :personne
validates :commune_id, :quartier,
presence: true
end
the Controller is:
class PersonneController < ApplicationController
def display_proprietaires
#proprietaires = Personne.all
##proprietaires = #proprietaires.proprietaire
end
def new_proprietaire
#provinces = Province.where(:parentId => nil)
#communes = Province.where.not(:parentId => nil)
#personne = Personne.new
#personne.build_proprietaire
end
def create_proprietaire
#proprietaire = Personne.new(proprietaire_params)
#proprietaire.build_proprietaire
respond_to do |format|
if #proprietaire.save
flash[:notice] = "succes"
flash[:type] = "success"
format.html { redirect_to action: :display_proprietaires }
else
flash[:notice] = "fail"
flash[:type] = "warning"
format.html { redirect_to action: :display_proprietaires }
end
end
end
def proprietaire_params
params.require(:personne).permit(:nom, :prenom, :tel, :email, proprietaire_attributes: [:id, :commune_id, :quartier]).except(:province, :commit)
end
end
the View is:
<%= form_for #personne, :url => url_for(:controller=>'personne', :action=>'create_proprietaire' ) do |f| %>
<div class="row">
<div class="col-xs-6 col-sm-6 col-lg-6">
<div class="form-group">
<%= f.label(:nom, 'Nom : ') %>
<%= f.text_field :nom, {class: "form-control", placeholder: 'Nom'} %>
</div>
<div class="form-group">
<%= f.label(:prenom, 'Prenom : ')%>
<%= f.text_field :prenom, {class: "form-control", placeholder: "Prenom"} %>
</div>
<div class="form-group">
<%= f.label(:tel, 'Telephone : ')%>
<%= f.text_field :tel, {class: "form-control", placeholder: "Telephone"} %>
</div>
<div class="form-group">
<%= f.label(:email, 'Email : ') %>
<%= f.text_field :email, {class: "form-control", placeholder: "Email"} %>
</div>
<div class="form-group">
<%= label_tag(:province, 'Province : ') %>
<%= select_tag(:province, options_for_select(#provinces.collect{|value| [value.denomination, value.id]}), {class: "form-control", id: "province", remote: true} ) %>
</div>
<%= f.fields_for :proprietaire do |proprio| %>
<div class="form-group">
<%= proprio.label(:commune_id, 'Commune : ') %>
<%= proprio.select :commune_id, options_for_select(#communes.collect{|value| [value.denomination, value.id]}),{}, {class: "form-control", id: "commune"} %>
</div>
<div class="form-group">
<%= proprio.label :quartier, "Quartier" %>
<%= proprio.text_field :quartier, {class: "form-control", placeholder: "Quartier"} %>
</div>
<% end %>
<%= f.submit "Enregistre", {class: 'btn btn-info'} %>
<% end %>
Routes:
resources :personne do
collection do
post :create_proprietaire
get :display_proprietaires
get :new_proprietaire
end
end
I'm new in RoR, When I try to save nothing happens, I'm getting this:
Could someone helps me on this. Thank you!
You have your association set to required but it's missing.
Associations are set to required by default in rails 5 so if you want to keep one empty you need to set optional:true on your association in model
I've got a problem with the creation of an object. The New-function ist working, but when i pass the object to the Create, the following error is thrown.
I want to add a Service when a ServiceProvider exists. Every User can create one ServiceProvider for himself. A ServiceProvider could have a few services.
I've also set the foreign-keys for the services-table in a MIgration-file via
"add_foreign_key :services, :service_provider"
I don't have an idea why the service_provider_id isn't transfered.
Error Output
ActiveRecord::RecordNotFound in ServicesController#create
Couldn't find ServiceProvider with 'id'=
Extracted source (around line #55):
private
def current_service_provider
Line 55: #current_service_provider = ServiceProvider.find(params[:id])
end
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"Z4s/ZzbbMmcXA1jAyFnEZZ/8RhS2ZO/UdI6xN5QkKQwXmJJOOo/PVsSdOUcuJvVpFJdaUi/rMtNJq5sAEdz89g==",
"service"=>{"name"=>"dsfg", "address"=>"asdf", "radius"=>"64655", "price"=>"45", "descr"=>"sdfagasrfsdgh"},
"commit"=>"Speichern"}
Models
class ServiceProvider < ApplicationRecord
belongs_to :user
has_many :services
validates :name, presence: true
validates :street, presence: true
validates :plz, presence: true
validates :location, presence: true
validates :user_id, presence: true
end
class Service < ApplicationRecord
belongs_to :service_provider
has_many :service_photos
validates :name, presence: true, length: {maximum: 50}
validates :address, presence: true
validates :price, presence: true
end
ServicesController
class ServicesController < ApplicationController
before_action :set_service, only: [:show, :edit, :update]
before_action :authenticate_user!, except: [:show]
def index
#service = current_user.services
end
def show
#service_photos = #service.service_photos
end
def new
#service = Service.new
end
def create
#service = current_service_provider.services.build(service_params)
if #service.save
if params[:images]
params[:images].each do |image|
service.service_photos.create(image: image)
end
end
#service_photos = #service.service_photos
redirect_to edit_service_path(#service), notice: "Gespeichert"
else
render :new
end
end
def edit
end
def update
end
private
def current_service_provider
#current_service_provider = ServiceProvider.find(params[:id])
end
def set_service
#service = Service.find(params[:id])
end
def service_params
params.require(:service).permit(:name, :address, :radius, :price, :descr)
end
end
Form
<div class="panel panel-default">
<div class="panel-heading">
Erstelle deinen Service
</div>
<div class="panel-body">
<div class="container">
<%= form_for #service, html: {multipart: true} do |f| %>
<div class="row">
<div class="form-group">
<label>Service Name</label>
<%= f.text_field :name, placeholder: "Servicename", class: "form-control" %>
</div>
</div>
<div class="row">
<div class="form-group">
<label>Adresse</label>
<%= f.text_field :address, placeholder: "Adresse", class: "form-control" %>
</div>
</div>
<div class="row">
<div class="form-group">
<label>Radius</label>
<%= f.text_field :radius, placeholder: "Radius", class: "form-control" %>
</div>
</div>
<div class="row">
<div class="form-group">
<label>Preis</label>
<%= f.text_field :price, placeholder: "Preis", class: "form-control" %>
</div>
</div>
<div class="row">
<div class="form-group">
<label>Beschreibung</label>
<%= f.text_area :descr, rows: 5, placeholder: "Beschreibung", class: "form-control" %>
</div>
</div>
<div class="rows">
<div class="col-md-4">
<div-form-group>
<span class="btn btn-default btn-file">
<i class="fa fa-cloud-upload fa-lg"></i>Fotos hochladen
<%= file_field_tag "images[]", type: :file, multiple: true %>
</span>
</div-form-group>
</div>
</div>
<div id="photos"><%= render 'service_photos/list' %></div>
<div class="actions">
<%= f.submit "Speichern", class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
</div>
In "create" action you try to find non-existing object. You can find object by 'id' after save that.
In your case params[:id] is not exist when "current_service_provider" method is calling.
i have a problem with my form who contains multiple object
When i go on my page "new" for create new team_member, i have this error :
unknown attribute 'team_member_id' for TeamMembersGame.
models/team_member.rb
class TeamMember < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
has_many :team_members_games
accepts_nested_attributes_for :team_members_games
has_many :team_members_weapons
has_many :team_members_champions
end
models/team_member_game.rb
class TeamMembersGame < ActiveRecord::Base
belongs_to :team_member
end
controllers/admin/team_members_controller.rb
class Admin::TeamMembersController < Admin::DashboardController
def new
#member = TeamMember.new
#member.team_members_games.build
end
def create
#member = TeamMember.new(member_params)
if #member.save
redirect_to edit_admin_team_member_path(#member.id), notice: 'Le membre a bien été creer'
else
render 'new'
end
end
def edit
#member = TeamMember.find(params[:id])
#member_game = #member.team_members_games
##member = TeamMember.joins(:TeamMembersChampion, :TeamMembersWeapon, :TeamMembersGame)
end
def update
#member = TeamMember.find(params[:id])
if #member.update_attributes(member_params)
# Handle a successful update.
redirect_to edit_admin_team_member_path(#member.id), notice: 'Le membre a bien été modifier'
else
render 'edit'
end
end
def destroy
TeamMember.destroy(params[:id])
redirect_to admin_team_members_path, notice: 'Le membre a bien ete supprimer'
end
private
def member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_games: [ :team_members_id, :name_game])
end
def member_games
params.require(:team_members_games).permit(:team_members_id, :name_game)
end
end
view/admin/new.html.erb
<%= form_for(#member, url: admin_team_members_path, html: { method: :post }, id: 'new_news') do |f| %>
<%= #member.inspect %>
<%= #member_games.inspect %>
<div class="row">
<div class="col s12">
<% #member.errors.full_messages.each do |msg| %>
<%= msg %>
<% end %>
</div>
</div>
<div class="row">
<div class="col s12 m6">
<div class="field input-field">
<%= f.label :name, "Nom" %>
<%= f.text_field :name, autofocus: true, :class => "" %>
</div>
</div>
</div>
<div class="row">
<div class="col s12">
<p class="bold">
Jeux :
</p>
</div>
<div class="col s12 m6">
<%= f.fields_for :team_members_games do |team_members_games_form| %>
<div class="field input-field">
<%= team_members_games_form.check_box :name_game, {:class => "filled-in", :id => "team_members_game_name_game"}, true, false %>
<%= team_members_games_form.label :name_game, "game" %>
</div>
<% end %>
</div>
</div>
<div class="row">
<div class="col s12">
<div class="btnlog actions">
<%= button_tag(type: 'submit', class: "btn") do %>
Publier <i class='material-icons right'>send</i>
<% end %>
</div>
</div>
</div>
<% end %>
thanks !
you are permitting team_members_id in your code instead of team_member_id
refactor your code to this:
def member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_games_attributes: [ :id, :team_member_id, :name_game])
end
Change permitted method name and parameters like this:-
def team_member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_games: [ :id, :name_game])
end
And use this method while creating team member:-
def create
#member = TeamMember.new(team_member_params)
if #member.save
redirect_to edit_admin_team_member_path(#member.id), notice: 'Le membre a bien été creer'
else
render 'new'
end
end
I have corrige some errors, but i haven't idea for get the id of team_member for the table team_member_games :
def team_member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_game_attributes: [ :id, :name_game])
end
no one element are add in my table team_members_games