Rails: undefined method '(MODELNAME)'? - ruby-on-rails

Hi I'm currently making a web app for uploading pics. There are users, albums, and photos. I'm having trouble trying to figure out what's going on when I try to edit a user's profile information. It is telling me that there is an undefined method 'album' NoMethodError in UsersController#update , but I don't even call album in my #update action.
def update
respond_to do |format|
if current_user.update_attributes(params[:user])
format.html { redirect_to current_user, notice: 'User successfully updated.'}
format.json { render json: current_user, status: :created, location: current_user }
else
format.html { render action: 'edit' }
format.json { render json: current_user.errors, status: :unprocessable_entity }
end
end
end
the error is specifically on the 2nd and 3rd lines of my update action. Here's the error:
app/controllers/users_controller.rb:45:in 'block in update'
app/controllers/users_controller.rb:44:inupdate'`
anyone know what the heck is going on?
edit form for users
<%= form_for(#user) do |f| %>
<div class="formhold">
<div class="field">
<% if #user.profilepic? %>
<%= image_tag #user.profilepic.url %>
<% end %>
<%= f.label :profilepic, "Profile Picture" %>
<%= f.file_field :profilepic %>
</div>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %>
<%= f.text_field :email %>
</div>
<div>
<%= f.submit 'Submit', :class => 'submitbutton' %>
</div>
<% if #user.errors.any? %>
<div id="error_exp">
<h2><%= pluralize(#user.errors.count, "error") %> occurred.</h2>
<ul>
<% #user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
<% end %>
<%= link_to "Back", user_path(#user) %>
user model
class User < ActiveRecord::Base
has_secure_password
attr_accessible :email, :name, :password, :password_confirmation, :profilepic
validates_presence_of :password, :on => :create
validates_format_of :name, :with => /[A-Za-z]+/, :on => :create
validates_format_of :email, :with => /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
validates_length_of :password, :minimum => 5, :on => :create
validates :album, :uniqueness => true
has_many :album_users
has_many :albums, :through => :album_users
accepts_nested_attributes_for :albums
has_many :friendships, :dependent => :destroy
has_many :friends, :through => :friendships, :conditions => "status = 'accepted'"
has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => "status = 'requested'", :order => :created_at
has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => "status = 'pending'", :order => :created_at
has_attached_file :profilepic
before_save { |user| user.email = email.downcase }
def name_with_initial
"#{name}"
end
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end

Try commenting out:
validates :album, :uniqueness => true
It is assuming that :album is an attribute/method of user and failing. You should handle your unique validations for albums in albums model, depending on your business logic. You can validate them based on user_id or some other attribute with :scope => [:user_id]

Related

Nested Forms in Rails 4.0.3

Im struggling with a nested form in Rails 4, this is the first time that I made a form of that kind. I have read lots of documentation but Im not able to make it work. :-(
I have two models: Person and Disease. One person can have many diseases and one disease belongs to person. Looks quite simple. The form for Diseases is not saved in the database.
Person Model:
class Person < ActiveRecord::Base
belongs_to :user
has_many :diseases, :dependent => :destroy #if you delete a person you also delete all diseases related
has_many :appointments, :dependent => :destroy
validates_presence_of :name, :email
validates :name, :length => {:maximum => 50, :too_long => "name is too long"}
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, format: { :with => VALID_EMAIL_REGEX , message: "is invalid" }
accepts_nested_attributes_for :diseases
end
Disease Model:
class Disease < ActiveRecord::Base
belongs_to :person
has_many :treatments
validates_presence_of :name, :start
validates :name, :length => {:maximum => 50, :too_long => "is too long, you can use the description field"}
validate :start_must_be_before_end, :unless => [:chronical, :unfinished], :presence => true
validates :end, :presence => true, :unless => [:chronical, :unfinished], :presence => true
validates :description, :length => {:maximum => 5000, :too_long => "is too long"}
def start_must_be_before_end
if self[:end] < self[:start]
errors.add(:start, "must be before end time")
return false
else
return true
end
end
end
People Controller:
def create
current_user
#person = Person.new(person_params)
#person.user_id = #current_user.id
respond_to do |format|
if #person.save
format.html { redirect_to #person, notice: 'Person was successfully created.' }
format.json { render action: 'show', status: :created, location: #person }
else
format.html { render action: 'new' }
format.json { render json: #person.errors, status: :unprocessable_entity }
end
end
end
def person_params
params.require(:person).permit(:name, :surname, :gender, :birthdate, :bloodtype, :user_id, :phone, :email, diseases_attributes: [:id, :description] )
end
Form:
<%= simple_form_for #person do |f| %>
<%= f.input :name %>
<%= f.input :email %>
<%= simple_fields_for :diseases do |my_disease| %>
<%= my_disease.input :description %>
<% end %>
<%= f.button :submit %>
<% end %>
Thanks a lot for your help.
The issue is with line <%= simple_fields_for :diseases do |my_disease| %>.It should be
<%= f.simple_fields_for :diseases do |my_disease| %>
This should work.
<%= simple_form_for #person do |f| %>
<%= f.input :name %>
<%= f.input :email %>
<%= f.simple_fields_for :diseases do |my_disease| %> #here
<%= my_disease.input :description %>
<% end %>
<%= f.button :submit %>
<% end %>
For more Info,see this API

Rails associated model is not updating in database

I'm trying to update my associated model, but it's not updating to the database and i'm not sure what to try next.
Model
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation,
:remember_me, :username, :login, :first_name,
:last_name, :home_phone, :cell_phone,
:work_phone, :birthday, :home_address,
:work_address, :position, :company, :user_details
has_one :user_details, :dependent => :destroy
accepts_nested_attributes_for :user_details
end
class UserDetails < ActiveRecord::Base
belongs_to :user
attr_accessible :home_phone, :position
end
Controller
# PUT /contacts/1/edit
# actually updates the users data
def update_user
#userProfile = User.find(params[:id])
respond_to do |format|
if #userProfile.update_attributes(params[:user])
format.html {
flash[:success] = "Information updated successfully"
render :edit
}
else
format.html {
flash[:error] = resource.errors.full_messages
render :edit
}
end
end
end
View
<%= form_for(#userProfile, :url => {:controller => "my_devise/contacts", :action => "update_user"}, :html => {:class => "form grid_6"}, :method => :put ) do |f| %>
<%= f.label :username, "Username" %>
<%= f.text_field :username, :required => "required" %>
<%= f.fields_for :user_details do |d| %>
<%= d.label :home_phone, "Home Phone" %>
<%= d.text_field :home_phone %>
<% end %>
<% end %>
<% end %>
Your attr_accessible should accept user_details_attributes, not just user_details.

Rails: trouble with pending / accepted invitations using :conditions hash

I'm currently trying to make an app for uploading pics. there are users, albums, pics. The catch is that there can be multiple owners for each album, so in the form to create an album there is a check box portion where you highlight your friends names and "invite them" to be an owner. However I'm trying to make it so that an invite has to be "accepted" before ownership is shared. I'm trying to do this using a join table (album_user) and having a album and pending_album, which are distinguished by their :status when created
This is my
albums/new.html.erb (no issue here)
<%= form_for ([#user, #album]), :html => { :id => "uploadform" } do |f| %>
<div class="formholder">
<%= f.label :name %>
<%= f.text_field :name %>
<br>
<label>Hosts</label>
<% #user.friends.each do |friend| %>
<%= friend.name %>
<%= check_box_tag 'album[user_ids][]', friend.id, #album.users.include?(friend) %>
<% end %>
<%= f.label :description %>
<%= f.text_area :description %>
<br>
<%=f.submit %>
</div>
<% end %>
albums controller (issue here with status)
def create
#user = User.find(params[:user_id])
#album = #user.albums.build(params[:album].merge(:status => 'accepted'))
#friends = #user.friends.find(params[:album][:user_ids])
if #user.save
for friend in #friends
AlbumUser.create({:user_id => friend.id, :album_id => #album.id, :status => 'pending'})
# friend.albums.build(params[:album].merge(:status => 'pending'))
end
redirect_to user_album_path(#user, #album), notice: 'Album was successfully created.'
else
render action: "new"
end
end
user model
class User < ActiveRecord::Base
has_secure_password
attr_accessible :email, :name, :password, :password_confirmation, :profilepic
validates_presence_of :password, :on => :create
validates_format_of :name, :with => /[A-Za-z]+/, :on => :create
validates_format_of :email, :with => /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
validates_length_of :password, :minimum => 5, :on => :create
# validates :album, :uniqueness => true
has_many :album_users
has_many :albums, :through => :album_users, :conditions => {status: 'accepted'}
has_many :pending_albums, :through => :album_users, :source => :album, :conditions => {status: 'pending'}
accepts_nested_attributes_for :albums
has_many :friendships, :dependent => :destroy
has_many :friends, :through => :friendships, :conditions => "status = 'accepted'"
has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => "status = 'requested'", :order => :created_at
has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => "status = 'pending'", :order => :created_at
has_attached_file :profilepic
before_save { |user| user.email = email.downcase }
def name_with_initial
"#{name}"
end
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
album model
class Album < ActiveRecord::Base
attr_accessible :name, :description, :user_ids, :status
validates_presence_of :name
has_many :album_users
has_many :users, :through => :album_users
has_many :photos
end
album_user model
class AlbumUser < ActiveRecord::Base
attr_accessible :album_id, :user_id, :status
belongs_to :album
belongs_to :user
end
ISSUE HERE: users/show.html.erb (where I have an icon for each album, but it seems like when albums are being created, they aren't saving as pending_albums even though their :status is 'pending'.
<% #user.pending_albums.each do |pending_album| %>
<div class="albumthumb">
<%= link_to image_tag(pending_album.photos ? pending_album.photos.first.avatar.url(:medium) : ("questionmark.png"), :size => "150x150"), user_album_path(#user, pending_album) %>
<br>
<%= pending_album.name %>
<% if signed_in? %>
<%= form_for(:album_user, :url => user_albums_path(:user_id => current_user.id, :album_id => pending_album.id)) do |f| %>
<%= f.submit "Accept Invitation" %>
<% end %>
<% end %>
</div>
<% end %>
<% #user.albums.each do |album| %>
<div class="albumthumb">
<%= link_to image_tag(!album.photos.empty? ? album.photos.first.avatar.url(:medium) : ("questionmark.png"), :size => "150x150"), user_album_path(#user, album) %>
<br>
<%= album.name %>
</div>
<% end %>
my issue is that the albums aren't saving as pending_albums. I thought my :conditions in the user model would help distinguish which are albums and which are pending albums? Everything seems to be falling under albums, even if they are supposed to be pending. Can anyone help?

Rails: Can't get fields_for to work inside a nested resource

I'm trying to add a fields_for attribute to a nested rails form. Any time I try to create a new object, it returns
Message(#58819400) expected, got
Array(#18903800) ...
app/controllers/discussions_controller.rb:53:in
`create'
If I try to access nested fields_for from forms based on non-nested resources (aka "form_for #parent" instead of "form_for [#parent, #child]" it works fine. Code below - any help with this really appreciated.
Controller:
# GET /discussions/new
# GET /discussions/new.xml
def new
#forum = Forum.find(params[:forum_id])
#discussion = Discussion.new
#discussion.messages.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #discussion }
end
end
def create
#forum = Forum.find_by_id(params[:forum_id])
#discussion = #forum.discussions.new(params[:discussion])
#discussion.user = current_user
respond_to do |format|
if #discussion.save
format.html { redirect_to([#forum, #discussion], :notice => 'Discussion was successfu#ly created.') }
format.xml { render :xml => [#forum, #discussion], :status => :created, :location => #discussion }
else
format.html { render :action => "new" }
format.xml { render :xml => #discussion.errors, :status => :unprocessable_entity }
end
end
end
Models:
class Forum < ActiveRecord::Base
belongs_to :user
has_many :discussions, :dependent => :destroy
validates :title, :presence => true
accepts_nested_attributes_for :discussions, :allow_destroy => true
end
class Discussion < ActiveRecord::Base
belongs_to :user
belongs_to :forum
has_many :messages, :dependent => :destroy
validates :title, :presence => true
end
class Message < ActiveRecord::Base
belongs_to :user
validates :user, :presence => true
validates :content, :presence => true
end
The view:
<%= form_for [#forum, #discussion] do |f| %>
<% if #discussion.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#discussion.errors.count, "error") %> prohibited this discussion from being saved:</h2>
<ul>
<% #discussion.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<%= f.fields_for :messages do |builder| %>
<%= builder.label :content, "Message" %>
<%= builder.text_area :content, :rows => 10 %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And finally, the routing:
resources :forums do
resources :discussions do
resources :messages
end
end
Any help with this really appreciated - I'm completely stumped.
Arghhh - really sorry folks...I just realised I'd forgot the accepts_nested_attributes_for in the discussions model, & consequently forums could access discussions, but discussions couldn't get down to messages.
Thanks anyhow.

Updating nested params not working.. whats wrong?

Im trying to update some nested params from a form. I can see that the parameters im getting from the form is correct, however the database dont get updated.
the view
<% form_for #order do |f| %>
<% f.fields_for :itemgroups do |ff, i| %>
<% ff.fields_for :items do |fff| %>
<%= ff.text_field :text, :id => "textField", :disabled => true %>
<%= ff.text_field :price, :class => "priceField", :disabled => true %>
<%= fff.check_box :registered, :class => i %>
<% end %>
<% end %>
<%= submit_tag 'Save', :disabled_with => "Saving..." %>
<% end %>
Itemgroup class
class Itemgroup < ActiveRecord::Base
belongs_to :order
has_many :items, :dependent => :destroy
has_one :kind
accepts_nested_attributes_for :items, :kind
end
Order class
class Order < ActiveRecord::Base
has_many :itemgroups, :dependent => :destroy
has_many :items, :through => :itemgroups, :dependent => :destroy
has_many :kinds, :through => :itemgroups
accepts_nested_attributes_for :itemgroups, :allow_destroy => true
validates_associated :itemgroups, :items ,:kinds
end
The important part of the controller.
def update
#order = Order.find(params[:id])
if #order.update_attributes(params[:order])
flash[:notice] = 'Order was successfully edited.'
redirect_to(#order)
else
flash[:notice] = 'An error occured.'
render(:action => :edit)
end
end
Change
<% f.fields_for :itemgroups do |ff, i| %>
<% ff.fields_for :items do |fff| %>
<%= ff.text_field :text, :id => "textField", :disabled => true %>
<%= ff.text_field :price, :class => "priceField", :disabled => true %>
<%= fff.check_box :registered, :class => i %>
<% end %>
To EDITED
<% f.fields_for :itemgroups do |ff, i| %>
<%= ff.text_field :text, :id => "textField", :disabled => true %>
<%= ff.text_field :price, :class => "priceField", :disabled => true %>
<% ff.fields_for :items do |fff| %>
<%= fff.check_box :registered, :class => i %>
<% end %>
and check
Fixed the problem!
class Order < ActiveRecord::Base
has_many :itemgroups, :dependent => :destroy
has_many :items, :through => :itemgroups, :dependent => :destroy
has_many :kinds, :through => :itemgroups
accepts_nested_attributes_for :itemgroups, :allow_destroy => true
# validates_associated :itemgroups, :items ,:kinds
end
the validates_associated line was removed. Then it worked

Resources