RubyOnRails | ActiveRecord::AssociationTypeMismatch - ruby-on-rails

I have a Stage Model, which belongs_to User Model. User Model has_many Stages.
When I try to create a New Stage, with an hidden_field containing the id of current_user ,
I have the following error :
ActiveRecord::AssociationTypeMismatch in StagesController#create
User(#63609336) expected, got String(#16545012)
Here's the array :
{"utf8"=>"✓",
"authenticity_token"=>"YD3VVr9Hntg/LEGjFAzu2roR5NGe6FPclew+zJOvGpY=",
"stage"=>{"user"=>"8",
"intitule"=>"er",
"entreprise"=>"er",
"secteur"=>"er",
"mission"=>"er",
"duree"=>"erea",
"annee_debut"=>"az",
"annee_fin"=>"z",
"comment"=>"az",
"site_entreprise"=>"az"},
"commit"=>"Create Stage"}
user_id is an Integer field.
The view :
<%= f.hidden_field :user, :value => current_user.id %>
Where is the problem ? I can't find any solution !
Thanks for your help.

replace with
<%= f.hidden_field :user_id, :value => current_user.id %>

I wouldn't recommend using hidden fields for this, as hidden fields can be modified by the user. I recommend doing something like current_user.stages.create in the controller instead, which will pre-populate the user_id in the created Stage.

Related

Rails Simple Form Select from Array - polymorphic associations

I am making an app in Rails 4. I use Simple Form for forms.
I have a profile model and an organisation model.
The associations are:
profile.rb
has_one :organisation, as: :orgable
organisation.rb
has_many :profiles
In my organisation table, I have an attribute called :org_type.
In my organisation form, I ask users to select from an array of types of organisation:
<%= f.input :org_type, :label => "Organisation type", collection: [ "University", "Research Organisation", "Company"] %>
In my profile form, I want to ask users which uni they study at.
I want to use the array of universities created within the organisation model.
I have a scope in my organisation model to filter out the universities:
scope :all_uni, -> { where(org_type: 'University') }
In my profile form I have:
<%= f.input :institution, :label => "Graduated from" %>
But this just has a text field.
I have tried to replace that line with an attempt at making a select function in my form which refers to my organisation model scope for all_uni. It looks like this:
<%= f.select(:institution, #organisation.all_uni.title.map { |value| [ value, value ] }) %>
It gives this error:
undefined method `all_uni' for nil:NilClass
I don't understand what this error message means, but I'm also not sure I'm on the right track with the form select field either. Any tips for where to look to get this working. I'm not sure how to go about setting up the select field in the first place?
ANOTHER ATTEMPT:
I have also tried using this in my profile form:
<%= f.select(:institution, #organisation.all_uni.title) %>
But I get the same error. I must be way off track - i've exhausted every option I can find.
ANOTHER ATTEMPT
I found this post
Rails Simple Form custom association select field
Taking the example in that solution, I tried:
<%= f.input :institution do %>
<%= f.select :institution, Profile.Organisation.all_uni.map{ |l| [l.title {:title => l.title.titlecase}] } %>
<% end %>
But, I get this syntax error. I've tried removing the => but keep getting more syntax errors.
syntax error, unexpected =>, expecting '}' ...i.map{ |l| [l.title {:title => l.title.titlecase}] } );#out... ... ^
Not a complete answer but according to what I know is, If you got 2 models then instead of using
profile.rb
has_one :organisation, as: :orgable
organisation.rb
has_many :profiles
You can simply use
profile.rb
belongs_to :organisation
organisation.rb
has_many :profiles

undefined method for text_field in ruby on rails

<%= f.text_field :quantity_available, :readonly => "readonly",:class=>"mg-text-field" %>
error:
undefined method `quantity_available' for #<:0xaf32b824>
In the new form I have shown "quantity_available" whose value I am getting through jquery and this field is only for displaying purpose so this has not been saved in model but I want to do same in edit form in which I am getting error as
how to resolve this?
You can define the field in the Model without it needing to be a persisted column in the table.
class Model < ActiveRecord::Base
attr_accessor :quantity_available
# other stuff here
end
For that purpose you can use text_field_tag. For more check on http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html
<%= text_field_tag 'quantity_available',nil, class: "mg-text-field", readonly: true %>

AssociationTypeMismatch with Rails form using Simple_form

Hello everyone: I'm trying to solve a problem with my form.
I have a product model where every product has one brand.
I'm using simple_form to create/update my products. In my original version I use
= simple_form_for [:admin, product] do |form|
...
= form.association :brand
...
Now I add a jquery select with ajax data loading and I change my input to:
= form.input_field :brand, input_html: { class: 'form-control select2' }
When I save my form I have an error:
ActiveRecord::AssociationTypeMismatch in Admin::ProductsController#create
Brand(#70355202593700) expected, got String(#70355134114860)
In my post params 'brand' is now a string equivalent to the ID of the brand I associate to my product, and I don't know how to fix the association.
Any hint?
For your input_field, it would probably need to be :brand_id because it's no longer being built as an association (that only works with the .association method).
If you are on Rails 3, be sure :brand_id is added to your model's attr_accessible expression.

Rails Parse Form Input

I'm using a form to transfer some data from one part of a controller to another (new to create), but I'm having some trouble with it. When I try to get the data after submitting the form, it just gives me a nil value.
Here's the form code:
<%= f.hidden_field :owner_id, :value => #tool.user_id %>
<%= f.hidden_field :tool_id, :value => #tool.id %>
<%= f.hidden_field :borrower_id, :value => current_user.id %>
And this is the create action in the controller:
def create
render text: params[:rental_agreement].inspect
#rental_agreement = RentalAgreement.create
#rental_agreement.owner_id = params[:owner_id]
# render text: #rental_agreement.inspect
end
When I hit the "Submit" button on the form, I see this:
{"owner_id"=>"3", "tool_id"=>"1", "borrower_id"=>"4"}
That's fine, but when I change which inspection renders (comment out the top line, uncomment the bottom), all it displays is:
#
And if I look in the Rails console at this object, all of the fields in it are nil (except the id and created_at fields).
I'm just trying to figure out how to assign the variables from the form (owner_id, tool_id, and borrower_id) to the rental_agreement variable. Any help is much appreciated!
Your create method seems wrong. Try this.
def create
#rental_agreement = RentalAgreement.new(params[:rental_agreement])
#rental_agreement.save
end

an example of a nested form in simple form?

I am still struggling both writing the controller and the actual form to be able to nest one form in another with an optional model?
I have Message which has many contacts
When submitting a message, I want to add a contact optionally.
I have this as an example:
= simple_form_for Message.new, :remote => true do |f|
#message_form
= f.error_messages
%p
= f.input :account_name, :url => autocomplete_account_name_messages_path, :size => 40, :as => :autocomplete
%p
= f.input :topic, :required => true,
:input_html => {:size => 30}
#add_contact_btn
= link_to "Add Contact"
#contact_form
= f.simple_fields_for :contactd do |fc|
= fc.input :email
= fc.input :first_name
= fc.input :last_name
= f.submit 'Give'
= f.submit 'Request'
For Message.rb model, I have the following:
has_many :contacts
accepts_nested_attributes_for :contacts, :reject_if =>:all_blank
Note: When I used :contacts in the simple_fields_for it didn't work, so it is singular. But the reverse for accepts_nested_attributess_for.
In my create controller for message, I included message.contacts.build
But right now I am still generating nil contacts.
Here is what I see passed as form data from google chrome:
message%5Baccount_name%5D:McKesson
message%5Btopic%5D:testing a contact
message%5Bbody%5D:testing this
sender_id:
receiver_id:23
message%5Bcontacts%5D%5Bemail%5D:888#gmail.com
message%5Bcontacts%5D%5Bfirst_name%5D:Ang
message%5Bcontacts%5D%5Blast_name%5D:Name
The correct method name is simple_fields_for (notice the plural)
Also, you need to keep the f. to call it on the simple_form object
I have a small project where I demonstrate how to use nested forms in simple-form, combined with cocoon (a gem I created to add/remove nested elements dynamically).
The project is on github.
Hope this helps.
In my create controller for message, I included message.contacts.build
But right now I am still generating nil contacts.
Make sure you put in your Message.rb model the ability for it to accept the attributes too.
class Message < ActiveRecord::Base
attr_accessible :contacts_attributes
has_many :contacts
accepts_nested_attributes_for :contacts
I know it doesn't answer your question fully but it may have just been this. When it comes to my project, it would return nil if i didn't include the :contacts_attributes, in my case it deals with products. Hope this helps even if I'm not using simple form as of now!
I faced similar issues working with nested forms. As suggested by JustinRoR you need to define
attr_accessible: contacts_attributes.
You should be able to test the hash in the ruby console ( I am not sure if you have tried this). I suggest you to print the params[:message] and use this to create message from console like Message.new(params[:message]). (Note params[:message] is what you get by printing the params[:message] hash).
Once it works in console it should work like charm

Resources