I have a new Match form:
EDIT:
= form_for(#match) do |f|
= f.label :match_date
= f.date_select :match_date, :order => [:day, :month, :year]
= f.label :player_ids, 'Select players'
= f.collection_select :player_ids, #players, :id, :lastname, {}, { multiple: true }
= f.fields_for :match_edits do |ff|
= ff.label :result
= ff.number_field :result, in: 0..10
%div
= f.button :submit
When I choose two players I want set for each one match result like this:
id: 1, match_id: 1, player_id: 1, result: 4
id: 2, match_id: 1, player_id: 2, result: 10
I'm new in rails and I don't know how to fix that
MatchController
class MatchesController < ApplicationController
respond_to :html
def index
#matches = Match.all
end
def show
#match = Match.find(params[:id])
#results = #match.match_edits
end
def new
#match = Match.new
#players = Player.all
2.times {#match.match_edits.build}
end
def create
#match = Match.new(match_params)
respond_to do |format|
if #match.save
format.html { redirect_to #match, notice: 'Match was successfully created.' }
format.json { render :show, status: :created, location: #match }
else
format.html { render :new }
format.json { render json: #match.errors, status: :unprocessable_entity }
end
end
end
private
def match_params
params[:match].permit :match_date, player_ids: [], :match_edits_attributes => [:id, :result]
end
end
MatchEdit model
class MatchEdit < ActiveRecord::Base
belongs_to :match
belongs_to :player
end
Match model
class Match < ActiveRecord::Base
has_many :match_edits
has_many :players, through: :match_edits
accepts_nested_attributes_for :match_edits, allow_destroy: true, reject_if: proc { |attrs| attrs['result'].blank? }
end
Schema.rb
ActiveRecord::Schema.define(version: 20150629144534) do
create_table "match_edits", force: :cascade do |t|
t.integer "match_id"
t.integer "player_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "result"
end
add_index "match_edits", ["match_id"], name: "index_match_edits_on_match_id"
add_index "match_edits", ["player_id"], name: "index_match_edits_on_player_id"
create_table "matches", force: :cascade do |t|
t.date "match_date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "players", force: :cascade do |t|
t.string "firstname"
t.string "lastname"
t.string "picture"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
You need to update your form to remove redundant code i.e.:
= ff.number_field :result, in: 0..10
Your form will look like:
= form_for(#match) do |f|
= f.label :match_date
= f.date_select :match_date, :order => [:day, :month, :year]
= f.label :player_ids, 'Select players'
= f.collection_select :player_ids, #players, :id, :lastname, {}, { multiple: true }
= f.fields_for :match_edits do |ff|
= ff.label :result
= ff.number_field :result, in: 0..10
%div
= f.button :submit
Your controller's new method is responsible to to provide multiple fields for result:
class MatchsController << ApplicationContoller
...
def new
...
2.times { #match.match_edits.build }
...
end
...
end
Your model should allow to accept nested attributes as following:
class Match
...
has_many :match_edits
accepts_nested_attributes_for :match_edits, allow_destroy: true,
reject_if: proc { |attrs| attrs['result'].blank? }
...
end
class MatchEdit
...
belongs_to :match
...
end
I found solution. Form should look like this:
= form_for(#match) do |f|
= f.label :match_date
= f.date_select :match_date, :order => [:day, :month, :year]
= f.fields_for :match_edits do |ff|
= ff.label :player_id, 'Select player'
= ff.collection_select :player_id, #players, :id, :lastname, {}, { multiple: false }
= ff.label :result
= ff.number_field :result, in: 0..10
%div
= f.button :submit
and in matches_controller:
def match_params
params[:match].permit :match_date, :match_edits_attributes => [:id, :result, :player_id]
end
Related
I wanted to create a three dropdown selects category>subcategory>susubcategory
I have followed this method here https://www.youtube.com/watch?v=ap551f2a_d0 with some changes to suit my needs. everything seemed fine and each dropdown gets populated based on the selection of the dropdown before but when I select any value in the dropdowns it does not keep it selected it just goes back to the default -Please select-! I am not sure where I went wrong.
note: I only have one module (categories for the categories and using the parant_id for the subcategories)
I would really appreciate it if someone can point me in the right direction. Thank you
my categories table
create_table :categories do |t|
t.string "name", limit: 255
t.text "description", limit: 65535
t.references "parent_id", limit: 4
t.boolean "important", default: false
t.integer "position", limit: 4, default: 0
t.timestamps
end
in modules category.rb
class Category < ApplicationRecord
validates :name, presence: true, uniqueness: true
has_many :jobs
belongs_to :parent_category, foreign_key: :parent_id, class_name: 'Category'
has_many :subcategories, foreign_key: :parent_id, class_name: 'Category'
has_many :subsubcategories, foreign_key: :parent_id, class_name: 'Category'
end
in modules job.rb
class Job < ApplicationRecord
validates :title,:category_id, :description, presence: true
validates :category, :presence => true
belongs_to :user
belongs_to :category , -> { order("name") }
end
dropdown_controller.js
import { Controller } from "#hotwired/stimulus";
// connect to data-controller="dropdown"
export default class extends Controller {
submit () {
this.element.requestSubmit();
}
}
in my jobs_controller.rb
before_action :authenticate_user!, except: [:index, :show]
before_action :set_categories
def index
#jobs = Job.all
end
def new
#categories = Category.where(parent_id: nil)
#subcategory = #subcategory&.category || []
#subcategories = #subcategories&.subcategories || []
#subsubcategories = #subsubcategories&.subsubcategories || []
#job = Job.new
end
def create
#job = Job.new(job_params.merge({ user: current_user }))
if #job.save
format.html { redirect_to root_path, notice: "Job was successfully created." }
else
render :new, status: :unprocessable_entity
end
end
private
def job_params
params.require(:job).permit(:title, :description,:category_id).merge(user: current_user)
end
def set_categories
#category = Category.find_by(id: params[:category].presence)
#categories = Category.find_by(id: params[:category].presence)
#subcategories = Category.find_by(id: params[:category].presence)
#subsubcategories = Category.find_by(id: params[:subcategories].presence)
end
end
views/jobs/new.html.erb
<%= turbo_frame_tag "form" do %>
<%= form_tag new_job_path, method: :get, data: { controller: "dropdown", action: "change->dropdown#submit" } do %>
<%= select_tag :category, options_from_collection_for_select(#categories, "id", "name", #category&.id ), prompt: "Select a category" %>
<%= select_tag :subcategories, options_from_collection_for_select(#subcategories, "id" , "name", #category&.id), prompt: "Select a subcategories category" %>
<%= select_tag :subsubcategories, options_from_collection_for_select(#subsubcategories, "id" , "name", #category&.id), prompt: "Select a subsubcategories category" %>
<% end %>
<% end %>
I think that you miss update select_tag after request successfully.
you create a new file views/jobs/new.turbo_stream.erb
Ex: The select_tag has category_id
<%= turbo_stream.update "category_id" do %>
<%= select_tag :category, options_from_collection_for_select(#categories, "id", "name", #category&.id ), prompt: "Select a category" %>
<% end %>
Make sure select_tag selected value with #category&.id (ex: #category&.id = 1)
I done it but i have 2 select_tags.
https://drive.google.com/file/d/1MBY3T0_O2TAE6zFUywDsEoIOjnxr1hMy/view?usp=share_link
P/S: Contact me if you wanna know anymore.
This was the solution to the problem:
my categories table
create_table :categories do |t|
t.string "name", limit: 255
t.text "description", limit: 65535
t.integer "parent_id", limit: 4
t.boolean "important", default: false
t.integer "position", limit: 4, default: 0
t.timestamps
end
in modules category.rb
class Category < ApplicationRecord
validates :name, presence: true
has_many :jobs
belongs_to :parent, foreign_key: :parent_id, class_name: 'Category' , :optional => true
has_many :subcategories, foreign_key: :parent_id, class_name: 'Category'
has_many :subsubcategories, foreign_key: :parent_id, class_name: 'Category'
end
in modules job.rb
class Job < ApplicationRecord
validates :title,:category_id, :description, presence: true
validates :category, :presence => true
belongs_to :user
belongs_to :category , -> { order("name") }
belongs_to :subcategories, class_name: "Category"
belongs_to :subsubcategories, class_name: "Category"
end
dropdown_controller.js
import { Controller } from "#hotwired/stimulus";
// connect to data-controller="dropdown"
export default class extends Controller {
submit () {
this.element.requestSubmit();
}
}
in my jobs_controller.rb
class JobsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
before_action :set_categories
def index
#jobs = Job.all
end
def new
#category = Category.find_by(id: params[:category])
#categories = Category.where(parent_id: nil)
#subcategories = #category.subcategories if #category
#subsubcategories = Category.where(:parent_id => params[:subcategories])
#job = Job.new
end
def create
#job = Job.new(job_params.merge({ user: current_user }))
if #job.save
format.html { redirect_to root_path, notice: "Job was successfully created." }
else
render :new, status: :unprocessable_entity
end
end
private
def job_params
params.require(:job).permit(:title, :description,:category_id).merge(user: current_user)
end
def set_categories
#category = Category.find_by(id: params[:category].presence)
#subcategory = Category.find_by(id: params[:subcategories])
#subsubcategory = Category.find_by(id: params[:subsubcategories])
end
end
views/jobs/new.html.erb
<%= turbo_frame_tag "form" do %>
<%= form_tag new_job_path, method: :get, data: { controller: "dropdown", action: "change->dropdown#submit" } do %>
<%= select_tag :category, options_from_collection_for_select(#categories, "id", "name", #category&.id ), prompt: "Select a category" %>
<%= select_tag :subcategories, options_from_collection_for_select(#subcategories || [], "id" , "name", #subcategory&.id), prompt: "Select a subcategories category" %>
<%= select_tag :subsubcategories, options_from_collection_for_select(#subsubcategories || [], "id" , "name", #subsubcategory&.id), prompt: "Select a subsubcategories category" %>
<% end %>
<% end %>
I am facing this error Couldn't find Variant without an ID
I don't get what is wrong :(
Stock belongs_to :variant
Variant has_many :stocks and belongs_to :product
Product
has_many :variants, inverse_of: :product, dependent: :destroy
has_many :stocks, through: :variants
accepts_nested_attributes_for :variants
stock.html.erb
<%= simple_form_for(Stock.new, url: admin_stocks_path) do |f| %>
<%= f.select :variant_id, options_from_collection_for_select(#product.variants, :id, :size),required: true %>
<%= f.input :quantity, required: true %>
<%= f.submit %>
<% end %>
stocks_controller.rb
class StocksController < ApplicationController
def show
#stock = Stock.find(params[:id])
end
def index
#stocks = Stock.all
#variants = Variant.all
end
def new
#stock = Stock.new
#product = Product.find(params[:product_id])
#variants = #product.variants
end
def create
find_variant
#product = #variant.product
#stock = Stock.new(stock_params)
if #stock.save
redirect_to stock_product_path(#product)
else
redirect_to stock_product_path(#product), alert: "Woops"
end
end
private
def stock_params
params.require(:stock).permit(:id, :quantity, :variant_id )
end
def find_variant
#variant = Variant.find(params[:variant_id])
end
end
I did fake the find_variantmethod with Variant.find(2) and it was working...
Why I can't find the :variant_id?
here is my table stocks from my schema.rb
create_table "stocks", force: :cascade do |t|
t.integer "quantity"
t.bigint "variant_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["variant_id"], name: "index_stocks_on_variant_id"
end
params[:variant_id] will not be the value. You meant stock_params[:variant_id]
I am doing an e-commerce.
I have products which have many options of products and at the same time they only have one variant.
I try to make the view to create the product have the option of add a block where appears the fields of the model and the changes of the variant which is associated to it. The problem is, for example, when i create a product with 5 options, when i update it increases to 10, and if i update it again, there will be 20. I can't find the problem why they are duplicating. I leave the codes below.
Schema of Product, option-product and variant
create_table "options_products", force: :cascade do |t|
t.integer "product_id"
t.float "price"
t.integer "stock"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "products", force: :cascade do |t|
t.string "name", default: "", null: false
t.text "description"
t.integer "category_id"
t.integer "vendor_id"
t.string "state", null: false
t.boolean "shippingInside", null: false
t.datetime "created_at"
t.datetime "updated_at"
t.integer "priceComparison"
t.string "image1_file_name"
t.string "image1_content_type"
t.integer "image1_file_size"
t.datetime "image1_updated_at"
t.float "price"
end
create_table "variants", force: :cascade do |t|
t.string "tipoVariant"
t.integer "options_product_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "controlStock"
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
end
Script for add and remove fields
$(document).on 'ready page:load', ->
$('form').on 'click', '.remove_field', (event) ->
$(this).prev('input[type=hidden]').val('1')
$(this).closest('fieldset').hide()
event.preventDefault()
$('form').on 'click', '.add_field', (event) ->
time = new Date().getTime()
regular_expression = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regular_expression,time))
event.preventDefault()
Product create and update
def create
#product = Product.new(product_params)
respond_to do |format|
if #product.save
format.html { redirect_to #product}
format.json { render :show, status: :created, location: #product }
else
format.html { render :new }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #product.update(product_params)
format.html { redirect_to #product}
format.json { render :show, status: :ok, location: #product }
else
format.html { render :edit }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
Product Params
def product_params
params.require(:product).permit(:name, :description, :state, :shippingInside, :vendor_id, :category_id, :priceComparison, :image1, :price, offer_attributes: [:status], options_products_attributes: [:price, :stock, variant_attributes: [:tipoVariant, :controlStock, :image]])
function in application helper to add association
def link_to_add_association(name, field, association)
new_object = field.object.send(association).klass.new
new_object_id = new_object.object_id
fields = field.fields_for(association, new_object, child_index: new_object_id) do |builder|
new_object.build_variant
render(association.to_s.singularize + '_field', f: builder)
end
link_to(name, '#', class: 'add_field', data: { id: new_object_id, fields: fields.gsub("\n", "") })
end
Product model
class Product < ActiveRecord::Base
#relations
belongs_to :category
belongs_to :vendor
has_one :offer, :dependent => :destroy
has_many :options_products, :dependent => :destroy
#accepts
accepts_nested_attributes_for :offer, allow_destroy: true
accepts_nested_attributes_for :options_products, allow_destroy: true
#validations
validates :name, presence:true
validates :name, uniqueness:true
validates :state, presence:true
validates :category_id, presence:true
validates :vendor_id, presence:true
has_attached_file :image1, styles: {medium: "300x300>", thumb: "150x150#" }
validates_attachment_content_type :image1, content_type: /\Aimage\/.*\z/
end
Option Product Model
class OptionsProduct < ActiveRecord::Base
belongs_to :product
has_one :variant, :dependent => :destroy
accepts_nested_attributes_for :variant, allow_destroy: true
end
Variant model
class Variant < ActiveRecord::Base
belongs_to :options_product
has_attached_file :image,
styles: {medium: "300x300>", thumb: "150x150#" }
validates_attachment_content_type :image,
content_type: /\Aimage\/.*\z/
end
_form of Product
= form_for #product, html: { multipart: true } do |f|
.row
.form-group.col-lg-6
.field
= f.file_field :image1
.row
.form-group.col-lg-6
.field
= f.text_field :name, :placeholder => 'Nombre', :class => 'form-control input-border-left'
.row
.form-group.col-lg-6
.field
= f.text_area :description, :placeholder => 'Descripcion', :class => 'form-control input-border-left'
.row
.form-group.col-lg-6
.field
= f.number_field :price, :placeholder => 'Precio a mostrar', :class => 'form-control input-border-left'
.row
.form-group.col-lg-6
.field
= f.label :Estado
%br/
= f.select :state, options_for_select(['Disponible', 'No disponible'])
.row
.form-group.col-lg-6
.field
= f.label :Envio
%br/
= f.check_box :shippingInside
.row
.form-group.col-lg-6
.field
= f.text_field :priceComparison, :placeholder => 'Precio anterior', :class => 'form-control input-border-left'
.row
.form-group.col-lg-6
.field
= f.label :vendor_id
%br/
= f.select :vendor_id, Vendor.all.collect { |vendor| [vendor.name, vendor.id] }
.row
.form-group.col-lg-6
.field
= f.label :category_id
%br/
= f.select :category_id, Category.all.collect { |category| [category.name, category.id] }
= f.fields_for :offer, #product.build_offer do |o|
= o.label :Oferta
%br/
= o.check_box :status
%br/
.row
= f.fields_for :options_products do |op|
= render 'options_product_field', f: op
= link_to_add_association 'Agregar variante', f, :options_products
%br/
.actions
= f.submit "Enviar", :class => 'button btn btn-primary bold'
options_product_field file
%fieldset
.row
.form-group.col-lg-6
.field
= f.text_field :price, :placeholder => 'Precio', :class => 'form-control input-border-left'
.row
.form-group.col-lg-6
.field
= f.text_field :stock, :placeholder => 'Stock', :class => 'form-control input-border-left'
= f.fields_for :variant do |v|
.row
.form-group.col-lg-6
.field
= v.text_field :tipoVariant, :placeholder => 'Tipo de variante', :class => 'form-control input-border-left'
.row
.form-group.col-lg-6
.field
= v.label :ControlarStock
%br/
= v.check_box :controlStock
.row
.form-group.col-lg-6
.field
= v.label :ImagenDeVariante
%br/
= v.file_field :image
= f.hidden_field :_destroy
= link_to 'Remover variante', '#', class: 'remove_field'
In product_params, you should specify id of options_products_attributes. Without id, attributes will be newly added to product model.
So, try
... options_products_attributes: [ :id, price, :stock, variant_attributes: [ :id, :tipoVariant, ...
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How do I make it automatically pull up the current users name when I go to the user profile page. Like I click on the "message me" button and instead of pulling all the users on the site, I want it to pull automatically the user I am looking at.
Right now when I press the "message me" button it pulls up all the users and I have to choose which user to send the message. What can I do? I can use <%= user.name %> to pull up the user but that isn't going to help me.
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#exampleModal" data-whatever="<%= #user.name%>">Message Me</button>
<%= f.collection_select (:recipients, User.all.collect {|p| [ p.name, p.id ] }, {}, { multiple: true , class: "chosen-select form-control" })%>
Full code:
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<%= form_for :conversation, url: :conversations, html: { class: "" } do |f| %>
<div class="panel2-signup">
<div class="panel-body-signup">
<div class="modal-body">
<form>
<div class="form-group">
To <%= f.collection_select (:recipients, User.all.collect {|p| [ p.name, p.id ] }, {}, { multiple: true , class: "chosen-select form-control" })%>
Subject:
<%= f.text_field :subject, class: "form-control" %>
Message:
<%= f.text_area :body, class: 'form-control', placeholder: "Type your message here", rows: 4 %>
</div>
</div>
Here is the db info
class CreateMailboxer < ActiveRecord::Migration
def self.up
#Tables
#Conversations
create_table :mailboxer_conversations do |t|
t.column :subject, :string, :default => ""
t.column :created_at, :datetime, :null => false
t.column :updated_at, :datetime, :null => false
end
#Receipts
create_table :mailboxer_receipts do |t|
t.references :receiver, :polymorphic => true
t.column :notification_id, :integer, :null => false
t.column :is_read, :boolean, :default => false
t.column :trashed, :boolean, :default => false
t.column :deleted, :boolean, :default => false
t.column :mailbox_type, :string, :limit => 25
t.column :created_at, :datetime, :null => false
t.column :updated_at, :datetime, :null => false
end
#Notifications and Messages
create_table :mailboxer_notifications do |t|
t.column :type, :string
t.column :body, :text
t.column :subject, :string, :default => ""
t.references :sender, :polymorphic => true
t.column :conversation_id, :integer
t.column :draft, :boolean, :default => false
t.string :notification_code, :default => nil
t.references :notified_object, :polymorphic => true
t.column :attachment, :string
t.column :updated_at, :datetime, :null => false
t.column :created_at, :datetime, :null => false
t.boolean :global, default: false
t.datetime :expires
end
#Indexes
#Conversations
#Receipts
add_index "mailboxer_receipts","notification_id"
#Messages
add_index "mailboxer_notifications","conversation_id"
#Foreign keys
#Conversations
#Receipts
add_foreign_key "mailboxer_receipts", "mailboxer_notifications", :name => "receipts_on_notification_id", :column => "notification_id"
#Messages
add_foreign_key "mailboxer_notifications", "mailboxer_conversations", :name => "notifications_on_conversation_id", :column => "conversation_id"
end
def self.down
#Tables
remove_foreign_key "mailboxer_receipts", :name => "receipts_on_notification_id"
remove_foreign_key "mailboxer_notifications", :name => "notifications_on_conversation_id"
#Indexes
drop_table :mailboxer_receipts
drop_table :mailboxer_conversations
drop_table :mailboxer_notifications
end
end
The ConversationsController.rb
class ConversationsController < ApplicationController
before_action :authenticate_user!
before_action :get_mailbox
def new
end
def index
end
def create
recipients = User.where(id: conversation_params[:recipients])
if
conversation = current_user.send_message(recipients, conversation_params[:body], conversation_params[:subject]).conversation
flash[:notice] = "Your message was successfully sent!"
redirect_to conversation_path(conversation)
else
flash[:alert] = "Error. Message was not created"
redirect_to new_conversation_path
end
end
def show
#receipts = conversation.receipts_for(current_user).order("created_at ASC")
# mark conversation as read
conversation.mark_as_read(current_user)
end
def reply
current_user.reply_to_conversation(conversation, message_params[:body])
flash[:notice] = "Your reply message was successfully sent!"
redirect_to conversation_path(conversation)
end
def trash
conversation.move_to_trash(current_user)
redirect_to mailbox_inbox_path
end
def untrash
conversation.untrash(current_user)
redirect_to mailbox_inbox_path
end
def delete
#mailbox.trash.each do |conversation|
conversation.receipts_for(current_user).update_all(deleted: true)
end
flash[:notice] = 'Your trash was cleaned!'
redirect_to mailbox_inbox_path
end
private
def conversation_params
params.require(:conversation).permit(:subject, :body,recipients:[])
end
def get_mailbox
#mailbox ||= current_user.mailbox
if #user = current_user
#post = current_user.posts.build
else
end
if #user = current_user
#post = current_user.posts.build
#purchased = Sale.where(buyer_email: current_user.email).order("created_at DESC").order("created_at DESC").paginate(page:params[:page], per_page: 1 )
#sales = Sale.where(seller_email: current_user.email).order("created_at DESC").order("created_at DESC").paginate(page:params[:page], per_page: 1 )
else
end
end
def message_params
params.require(:message).permit(:body, :subject)
end
end
Looking at your action filters it looks like you are using the devise gem for user management.
To get the current authenticated user in devise you can use the helper method current_user.
I have an "Accept/Reject" workflow for tasks (created with nested forms via Cocoon). Basically,
if 1) the current user is the assignee (current_user.email == :assignee), 2) the current user is not the creator (current_user.email != :creator), and 3) the task has not been accepted (true) or rejected (false) i.e. nil (:accepted != nil),
then 1) show the creator (:creator) and 2) the enabled field to accept or reject (f.select :accepted)
When I am using these if statements, the fields (creator & accept/reject) are showing regardless of whether the condition is true or false. In addition, I am not allowed to use current_user.email in my if statement even though I can print it just fine.
Here's my code:
_task_fields.html.haml (views > projects)
.nested-fields
.field
= f.label :description
= f.text_field :description
.field
= f.label :done
= f.check_box :done
- if (:accepted != nil) && (:creator != nil)
.field
= f.label :creator
= f.text_field :creator, :disabled => true
.field
= f.label :accepted, "Accept or Reject"
= f.select :accepted, options_for_select([nil,['Accept',true],['Reject',false]])
.field
= current_user.email
= f.label :priority
- if :priority == nil
= f.select :priority, options_for_select(["None","Low","High"],"None")
- else
= f.select :priority, options_for_select(["None","Low","High"],:priority)
.field
= f.label :assignee
= f.select :assignee, User.pluck(:email), :prompt => "Select One"
= link_to_remove_association "remove task", f, :class => "btn btn-default btn-sm"
_form.html.haml (views > projects)
= form_for #project do |f|
.jumbotron
%h3 Project Settings
.field
= f.label :title
= f.text_field :title
#category
.form_row
= f.label :category
- if #project.category == "process"
= f.radio_button :category, "process", :checked => 'checked'
= "process"
= f.radio_button :category, "checklist", :checked => #project.category == "checklist"
= "checklist"
- else #project.category == "checklist"
= f.radio_button :category, "process", :checked => #project.category == "process"
= "process"
= f.radio_button :category, "checklist", :checked => 'checked'
= "checklist"
.field
= f.label :description
= f.text_field :description
- if #project.category == "process"
%h3 Steps
#steps
= f.fields_for :steps do |step|
%ul.list-group
= render 'step_fields', :f => step
.links
= link_to_add_association 'add step', f, :steps
- if #project.category == "checklist"
#tasks
= f.fields_for :tasks do |task|
.jumbotron
= render 'task_fields', :f => task
.links
.jumbotron
= link_to_add_association 'add task', f, :tasks, :partial => 'projects/new_task_fields', :class => "btn btn-default btn-sm"
= f.submit
projects_controller.rb (just the relevant parts)
def update
respond_to do |format|
if #project.update(project_params)
format.html { redirect_to #project, notice: 'Project was successfully updated.' }
format.json { render :show, status: :ok, location: #project }
format.js
else
format.html { render :edit }
format.json { render json: #project.errors, status: :unprocessable_entity }
format.js
end
end
end
def project_params
params.require(:project).permit(:title, :category, :description, tasks_attributes: [:id, :description, :done, :priority, :assignee, :creator, :created_at, :accepted, :completed_at, :_destroy])
end
schema.rb (just the relevant parts)
create_table "tasks", force: true do |t|
t.string "description"
t.boolean "done"
t.integer "project_id"
t.datetime "created_at"
t.datetime "updated_at"
t.datetime "due"
t.boolean "started"
t.boolean "active"
t.string "repeat"
t.integer "time_limit"
t.string "priority"
t.string "assignee"
t.string "creator"
t.datetime "started_at"
t.datetime "completed_at"
t.datetime "paused_at"
t.datetime "resumed_at"
t.integer "time_spent"
t.boolean "accepted"
end
add_index "tasks", ["project_id"], name: "index_tasks_on_project_id"
I can add more files if necessary but I doubt my controller/model seems to be the issue. Thanks and appreciate any input.
- if (:accepted != nil) && (:creator != nil)
The above statement will always be true, because you are checking if a symbol is not equal to nil which is always true
You should check something like
- if (#project.accepted != nil && #project.creator != nil)