Reputation:
Two models I have created i.e "User" and "Communication", and schema is below:
user model scheme:
id | name | Email | SkillType | user_Need
1 | ijk | [email protected] | Mentor | Ap Chinese
2 | mno | [email protected] | Protege | Ap Biology
Communication model schema:
id | UserID | CommunicationMode | CommunicationDetail
1 | 1 | Phone | 1234567890
2 | 1 | Email | [email protected]
In User model i have has_many
relation with Communication, and in Communication model i have belongs_to :user
I am adding communication preferences when user sign ups to the application, and in setting, i am trying to display that user's communication preferences in separate controls.when user submits the settings page, i want to delete each record in Communication that is related to current_user, its working fine and the code is below
Communication.delete_all(:UserID => current_user.id)
But when I update them from new action in controller, the records are not updating from Communication. and below is my "new" action code:
def create
@user_basic=User.find(current_user.id)
@students=Students.all
@entrepreneurs=Entrepreneurs.all
@veterans=Veterans.all
@user_communication=Communication.where(:UserID => current_user.id)
Communication.delete_all(:UserID => current_user.id)
@user_communication.update_attributes(:CommunicationMode => "CommunicationDetail")
render 'new'
end
And I am getting below error at this line '@user_communication.update_attributes(:CommunicationMode => "CommunicationDetail")'
Error:
undefined method `update_attributes'
Kindly suggest me where I make mistake, waiting for reply. Thanks
Upvotes: 0
Views: 650
Reputation: 76774
Your syntax is incorrect
.destroy_all
removes the elements you've specified. The problem is you're then trying to call the exact same elements with .update_attributes
You'd need something like this:
def create
@user_basic = User.find(current_user.id)
@students = Students.all
@entrepreneurs = Entrepreneurs.all
@veterans = Veterans.all
@user_communication = @user_basic.communications #-> based on has_many / belongs_to assoc
@user_communication.update_all(CommunicationMode: "CommunicationDetail")
render 'new'
end
If you want to just update records, you don't need to remove them first. You can just use update_attributes
to insert the new data into the db
Upvotes: 0
Reputation: 8295
I don't get what you are trying to do,
@user_communication=Communication.where(:UserID => current_user.id)
Communication.delete_all(:UserID => current_user.id)
@user_communication.update_attributes(:CommunicationMode => "CommunicationDetail")
you delete the communications for the given user and then you try to update his attributes with CommunicationMode = "CommunicationDetail"
.
So, the update fails because there is no record. I am almost sure that there is a problem with the logic you try to apply.
Upvotes: 1