I am getting the error NoMethodError in CarController#add - ruby-on-rails

NoMethodError in CarController#add
undefined method `user_id=' for #<Car:0x7160c70>
RAILS_ROOT: C:/Users/Jatinder/BitNami RubyStack projects/mercedes_mod 2
add.html (for adding car)
<h1>Ask a Question or Discuss Your Car</h1>
<%= error_messages_for :car %>
<br>
<p>You can ask anything related to cars even if its not a Mercedes!</p>
<% form_for :car do |f| %>
<p>
<%= f.label :name, "Title of Question" %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :description, "Describe Your Question" %>
<%= f.text_area :description %>
</p>
<p>
<%= f.submit "Add" %>
</p>
<% end %>
def add in car_controller.rb:
def add
#title = "Ask a New Question"
if request.post?
#car = Car.new(params[:car])
#car.user_id = User.logged_in(session).id
if #car.save
flash[:notice] = "Car #{#car.name} added!"
redirect_to :controller => :car, :action => :index
end
end
end
car.rb model:
class Car < ActiveRecord::Base
belongs_to :user
belongs_to :subject
validates_presence_of :name, :description
end
routes.rb
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
map.resources :car, :users => { :delete => :get }
map.root :controller => "main"
map.root :controller => "car", :action => "destroy"
end
create_cars migration:
class CreateCars < ActiveRecord::Migration
def self.up
create_table :cars do |t|
t.interger :user_id
t.string :name
t.string :description
t.timestamps
end
end
def self.down
drop_table :cars
end
end

Two errors:
user_id is declared as an "inte r ger"
I think you meant to write user = rather than user_id =

Chuck is correct. Your user_id is declared as an "interger". Consider using
t.references :user
instead of t.integer :user_id.
Also verify that your user model declares it's connection to the car model using has_one or has_many.
If User.logged_in(session) returns a User model object, you can do #car.user = User.logged_in(session) If not your code should work fine.

I want to know how is relation defined in your User model, might be you not defined the relation in User model due which its not able to find the user_id

Related

No route matches {:action=>"show", :controller=>"items"} missing required keys: [:id]

Update: I've been trying to debug my files, so most of the files have changed recently
I am getting a strange error when trying to use a "new" action to my items_controller. Essentially, a wishlist has_many items and an item belongs_to wishlist. The error message is as follows:
Code
Here is my items_controller:
class ItemsController < ApplicationController
def show
#item = Item.find(params[:id])
end
def new
#item = Item.new
end
def create
#item = Item.new(item_params)
if #item.save
redirect_to "/wishlist", :notice => "Success!"
else
redirect_to "/wishlist", :notice => "Failure, try again later!"
end
end
def edit
#item = Item.find(params[:id])
end
def update
#item = Item.find(params[:id])
if #item.update_attributes(item_params)
redirect_to(:action => 'show', :id => #item.id)
else
render 'edit'
end
end
private
def item_params
params.require(:item).permit(:name,:size,:qty,:priority)
end
private
def create_params
params.require(:item).permit(:name,:size,:qty,:priority,:wishlist_id)
end
end
And my routes.rb:
Rails.application.routes.draw do
get '/wishlist' => 'wishlists#index', as: :wishlists
get '/wishlist/:id' => 'wishlists#show', as: :wishlist
get '/wishlist_items/new' => 'items#new'
get '/wishlist_items/:id' => 'items#show', as: :items
get '/wishlist_items/:id/edit' => 'items#edit', as: :edit_items
patch '/wishlist_items/:id' => 'items#update'
resources :items
And finally, my new.html.erb for the items model:
<h1>New Item</h1>
<div class="wishlist-new">
<% if true %>
<%= form_for(#item) do |f| %>
<%= f.text_field :name, :placeholder => "Name" %>
<%= f.text_field :size, :placeholder => "Specifications" %>
<%= f.text_field :qty, :placeholder => "Quantity" %>
<%= f.text_field :priority, :placeholder => "Priority" %>
<%= f.text_field :id, :placeholder => "Wishlist ID" %> # changing :id to :wishlist_id doesn't seem to do anything
<%= f.submit "Create Item", class: "btn-submit" %>
<% end %>
<% end %>
</div>
My migration files (so you know how my databases are structured:
# Migration file for items
class CreateItems < ActiveRecord::Migration
def change
drop_table :items
create_table :items do |t|
t.string :name
t.string :size
t.string :qty
t.integer :priority
t.references :wishlist
t.timestamps
end
end
end
# Migration File for Wishlists
class CreateWishlists < ActiveRecord::Migration
def change
drop_table :wishlists
create_table :wishlists do |t|
t.string :title
t.timestamps
end
end
end
Attempts to Debug
It seems like the routes.rb is sending requests to different methods in the items_controller because the error seems to say that /wishlist_items/new is accessing a show method even though its new method takes priority. To support this, the page loads properly when I comment out get '/wishlist_items/:id' => 'items#show', as: :items in the routes file. What happens is the page loads properly, and the Item is created properly (when I fill out the form) except that when I go into the console, it says that the Item created has a property of wishlist_id: nil even though I specified for it to be 1 in the form.
The method mentioned above has two problems: (1) it doesn't work entirely correctly, and (2) it becomes impossible to show a specific Item in the wishlist.
The error occurs before the inner section of the form_for is loaded, so the problem either is (a) a weird routing thing (as mentioned above) or (b) something weird happening to the #item variable.
Thanks in advance!

Rails 4: "wrong number of arguments (2 for 1)"

I know this is a pretty standard error, but I could not figure out a solution to this particular solution from other questions.
I am following this coderwall tutorial about Creating a Scoped Invitation System for Rails.
I have four models, as follows:
class User < ActiveRecord::Base
has_many :administrations
has_many :calendars, through: :administrations
has_many :invitations, :class_name => "Invite", :foreign_key => 'recipient_id'
has_many :sent_invites, :class_name => "Invite", :foreign_key => 'sender_id'
end
class Calendar < ActiveRecord::Base
has_many :administrations
has_many :users, through: :administrations
has_many :invites
end
class Administration < ActiveRecord::Base
belongs_to :user
belongs_to :calendar
end
class Invite < ActiveRecord::Base
belongs_to :calendar
belongs_to :sender, :class_name => 'User'
belongs_to :recipient, :class_name => 'User'
end
And this is the migration for the Invite model:
class CreateInvites < ActiveRecord::Migration
def change
create_table :invites do |t|
t.string :email
t.integer :calendar_id
t.integer :sender_id
t.integer :recipient_id
t.string :recipient_role
t.string :token
t.timestamps null: false
end
end
end
The goal of the Invite model is to allow Users to invite other Users to join a particular Calendar.
The create Invite form is embedded in the Calendar edit view, as follows:
<h2>Edit <%= #calendar.name %> calendar</h2>
<%= render 'form' %>
<h2>Invite new users to <%= #calendar.name %> calendar</h2>
<%= form_for #invite , :url => invites_path do |f| %>
<%= f.hidden_field :calendar_id, :value => #invite.calendar_id %>
<%= f.label :email %>
<%= f.email_field :email %>
<%= f.label "Role" %>
<%= f.radio_button(:recipient_role, "Editor") %>
<%= f.label "Editor" %>
<%= f.radio_button(:recipient_role, "Viewer") %>
<%= f.label "Viewer" %>
<%= f.submit 'Send' %>
<% end %>
<%= link_to 'Show', calendar_path %> |
<%= link_to 'Back', calendars_path %>
Here is the corresponding Calendars#Edit:
def edit
#user = current_user
#invite = #calendar.invites.build
authorize #calendar
end
And here is the InvitesController:
class InvitesController < ApplicationController
def create
#invite = Invite.new(invite_params) # Make a new Invite
#invite.sender_id = current_user.id # set the sender to the current user
if #invite.save
InviteMailer.invite(#invite, new_user_registration_path(:invite_token => #invite.token)).deliver #send the invite data to our mailer to deliver the email
else
format.html { render :edit, notice: 'Invitation could not be sent.' }
end
end
private
def invite_params
params.require(:invite).permit(:email)
end
end
Last but not least, here is the InviteMailer:
class InviteMailer < ApplicationMailer
def invite(invite)
#link = new_user_registration_path invite_token: invite.token
mail to: invite.email, subject: "Calendy Invitation"
end
end
When I visit http://localhost:3000/calendars/3/edit and submit the Invite create form, I get the following error:
ArgumentError in InvitesController#create
wrong number of arguments (2 for 1)
class InviteMailer < ApplicationMailer
def invite(invite)
#link = new_user_registration_path invite_token: invite.token
mail to: invite.email, subject: "Calendy Invitation"
end
My instinct would be to replace:
InviteMailer.invite(#invite, new_user_registration_path(:invite_token => #invite.token)).deliver
With:
InviteMailer.invite(#invite).deliver
But I am not sure this is actually the right solution.
Any idea about how to fix this error?
May be changing the invite to allow an extra argument like below should work too
class InviteMailer < ApplicationMailer
def invite(invite, link)
#link = link
mail to: invite.email, subject: "Calendy Invitation"
end
end
My instinct would be to replace:
InviteMailer.invite(#invite, new_user_registration_path(:invite_token => #invite.token)).deliver
With:
InviteMailer.invite(#invite).deliver
Yes, that would be fine, since you're doing the same - your InviteMailer#invite stores this data itself in #link variable:
class InviteMailer < ApplicationMailer
def invite(invite)
#link = new_user_registration_path invite_token: invite.token
mail to: invite.email, subject: "Calendy Invitation"
end
end

Why doesn't my user follow/unfollow button work?

I am working on building an application (following Michael Hartl's chapter 11) where users can follow projects that are created by other users.
I created a ProjectRelationship model to hold two components: follower_id for the users and projectuser_id for the projects. The foreign keys have been set up as such.
Right now, my _follow_form.html.erb page renders "follow" or "unfollow" depending on whether the current_user is following the project. Please see my code below and see what I am missing.
Right now, the follow button is generated on each project show page. But when I click the button follow button that is generated by _follow.html.erb, it does not seem to follow the project or update the count when I call #project.followers.count as the POST is not happening.
And thus, when I click follow button, the URL becomes all jumbled. See example:
#Goes from
domain.com/projects/21
#to
domain.com/projects/21?utf8=%E2%9C%93&authenticity_token=5EQmU0EkHB5yKDYakqL78piMWzZl0CfdpHFEqBeQiN4%3D&project_relationship%5Bprojectuser_id%5D=21&commit=Follow%22
**Update:
It seems to work now, but I'm not sure if I really changed anything but got rid of the follower_id index :unique => true through a migration change.
schema.rb
create_table "project_relationships", :force => true do |t|
t.integer "follower_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "projectuser_id"
end
add_index "project_relationships", ["follower_id"], :name => "index_project_relationships_on_follower_id", :unique => true
add_index "project_relationships", ["projectuser_id"], :name => "index_project_relationships_on_projectuser_id"
routes.rb
resources :projects do
resources :comments
member do
get :following
end
end
resources :project_relationships, only: [:create, :destroy]
project_relationship.rb
class ProjectRelationship < ActiveRecord::Base
attr_accessible :projectuser_id
belongs_to :user, foreign_key: "follower_id"
belongs_to :project, foreign_key: "projectuser_id"
end
project.rb
has_many :project_relationships, foreign_key: "projectuser_id"
has_many :favorited_by, through: :project_relationships, source: :user
user.rb
has_many :project_relationships, foreign_key: "follower_id"
has_many :followed_projects, through: :project_relationships, source: :project
def following_project?(project)
project_relationships.find_by_follower_id(project.id)
end
def follow_project!(project)
project_relationships.create!(projectuser_id: project.id)
end
def project_unfollow!(project)
project_relationships.find_by_projectuser_id(project.id).destroy
end
project_relationships_controller.rb
class ProjectRelationshipsController < ApplicationController
def create
#project = Project.find(params[:project_relationship][:projectuser_id])
current_user.follow_project!(#project)
redirect_to #project
end
def destroy
#project = ProjectRelationship.find(params[:id]).followed_project
current_user.project_unfollow!(#project)
redirect_to #project
end
end
projects/show.html.erb
<%= render 'follow_form' if signed_in? %>
projects/_follow_form.html.erb
<% if current_user.following_project?(#project) %>
<%= render 'unfollow' %>
<% else %>
<%= render 'follow' %>
<% end %>
projects/_follow.html.erb
<%= form_for(current_user.project_relationships.build(projectuser_id: #project.id)) do |f| %>
<div><%= f.hidden_field :projectuser_id %></div>
<%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>
projects/_unfollow.html.erb
<%= form_for(current_user.project_relationships.find_by_projectuser_id(#project),
html: { method: :delete }) do |f| %>
<%= f.submit "Unfollow", class: "btn btn-large" %>
<% end %>
First of all - if you run projectfollow!(project) and projectunfollow!(project) in your console (with a user, project etc) do they work properly?
For your forms try the following instead and see if it works:
<%= form_for(current_user.project_relationships.build, url: project_relationships_path(project_id: #project.id)) do |f| %>
Then in your project relationships controller:
class ProjectRelationshipsController < ApplicationController
def create
#project = Project.find(params[:project_id])
current_user.projectfollow!(#project)
redirect_to #project
end
end
So if your create URL is /project_relationships (via POST), the above should post to /project_relationships?project_id=5 and then the controller can find that project.
Also, try to rename your methods so they make sense:
def following_project?(project)
end
def follow_project!(project)
end
def unfollow_project!(project)
end
Now current_user.following_project?(project) makes a lot of sense!
Update
Ok, I think the following is the problem, in your create action you're getting the id from the params:
#project = Project.find(params[:project_relationship][:projectuser_id])
However in your form you're not setting the value of the hidden field:
<%= f.hidden_field :projectuser_id %>
Change it to the following and see if it works:
<%= f.hidden_field :projectuser_id, value: #project.id %> # or wherever the id is from
The problem was that my follow/unfollow form was embedded in another form which caused the error. Once taken out, worked!

I can't insert to my database rails

i can't insert to my database whats is my problem?
it's bowling game and i have two tables with name "Player" and "Result"
view
<%= form_for player_new_path(#player) do |f|%>
<div class="text_field">
<p>
<%= f.label "Spelare namn" %>
<%= f.text_field :name %>
</p>
<p>
<%= f.submit "Lägg till en spelare"%>
</p>
</div>
Controller
def create
#player = Player.new(params[:players])
if #player.save
redirect_to players_new_path
else
render :action => "new"
end
end
Not work :/
my model:
class Player < ActiveRecord::Base # attr_accessible :title, :body
belongs_to :result
end
and my migrations:
class CreatePlayers < ActiveRecord::Migration
def change
create_table :players do |t|
t.string "name"
t.references :results
t.timestamps
end
Check your params hash. I bet the key isn't 'players', it's probably 'player'.
#player = Player.new(params[:players]) should probably be #player = Player.new(params[:player]) (You are getting a single player as a param)
Otherwise, what error are you getting

NoMethodError in CarController#add undefined method `user_id=' for #<Car:0x71451d8> [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
NoMethodError in CarController#add
undefined method `user_id=' for #<Car:0x7160c70>
RAILS_ROOT: C:/Users/Jatinder/BitNami RubyStack projects/mercedes_mod 2
add.html (for adding car)
add.html in /views/car
<h1>Ask a Question or Discuss Your Car</h1>
<%= error_messages_for :car %>
<br>
<p>You can ask anything related to cars even if its not a Mercedes!</p>
<% form_for :car do |f| %>
<p>
<%= f.label :name, "Title of Question" %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :description, "Describe Your Question" %>
<%= f.text_area :description %>
</p>
<p>
<%= f.submit "Add" %>
</p>
<% end %>
def add in car_controller.rb:
def add
#title = "Ask a New Question"
if request.post?
#car = Car.new(params[:car])
#car.user_id = User.logged_in(session).id
if #car.save
flash[:notice] = "Car #{#car.name} added!"
redirect_to :controller => :car, :action => :index
end
end
end
car.rb model:
class Car < ActiveRecord::Base
belongs_to :user
belongs_to :subject
validates_presence_of :name, :description
end
routes.rb
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
map.resources :car, :users => { :delete => :get }
map.root :controller => "main"
map.root :controller => "car", :action => "destroy"
end
create_cars migration:
class CreateCars < ActiveRecord::Migration
def self.up
create_table :cars do |t|
t.interger :user_id
t.string :name
t.string :description
t.timestamps
end
end
def self.down
drop_table :cars
end
end
Your migration has a typo. You should have t.integer, not t.interger on your :user_id. Also, make sure to run rake db:migrate in your console before running your app.
Your migration is busted:
t.interger :user_id
You're looking for an integer.

Resources