Reputation: 707
I have a model Messages, for which I have a recipient_list which saves as a string. For whatever reason on save, all of my parameters other than the recipient_list are being saved, with only the recipient_list being left out. I'm stumped as to what the cause for this may be.
Model:
class Message < ActiveRecord::Base
attr_accessible :content, :sender_id, :recipient_list
attr_reader :recipient_list #necessary for jquery-token-input
belongs_to :sender, class_name: "User"
validates :content, presence: true
validates :sender_id, presence: true
validates :recipient_list, presence: true
def recipient_list=(recipient) #jquery-token-input
self.recipient_ids = recipients.split(",")
end
end
Controller:
def create
@message = current_user.sent_messages.build(params[:message])
if @message.save
flash[:success] = "Message Sent."
redirect_to '/users/'+current_user.id.to_s+'/messages'
else
redirect_to '/users/'+current_user.id.to_s+'/messages'
end
end
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"WlStV4ogguSX72vrZp10zJbucS5MTL1pT1DLt06qjcw=",
"message"=>{"recipient_list"=>"1,2",
"content"=>"foobar123",
"sender_id"=>"1"},
"commit"=>"Send"}
Result:
#<Message id: 32, content: "foobar123", sender_id: 1, recipient_list: "", created_at: "2012-08-22 19:38:44", updated_at: "2012-08-22 19:38:44">]
What might be the problem that is keeping the recipient_list from being saved in this case?
Edit:
Par Ylan's note I set out to see why it was working despite the difference in variable name. upon messing with it, I realized that it actually was only working that way if i made recipient -> recipients or the reverse the it would stop working.
Fiddled with it, and based on Nash's suggestion came up with the following:
def recipient_list=(ids)
recipient_list = ids.split(",")
super(recipient_list)
end
#<Message id: 42, content: "foobar123", sender_id: 1, recipient_list: "---\n- '1'\n", created_at: "2012-08-22 21:58:46", updated_at: "2012-08-22 21:58:46">]
So now the recipient_list is being saved, I just have to figure out how to remove all the unecessary garble and get just the '1' lol. Any further suggestions?
Edit #2: After adding serialize :recipient_list, Array
#<Message id: 43, content: "foobar123", sender_id: 1, recipient_list: ["1", "2"], created_at: "2012-08-22 22:10:46", updated_at: "2012-08-22 22:10:46">]
is the new out put which is what i was going for. We worked together on this one. Thanks you two.
Upvotes: 1
Views: 273
Reputation: 1786
I believe you have a typo in your writter method. You are passing an argument named recipient
, but call recipients.split(",")
. Change either one and you should be set.
Upvotes: 1
Reputation: 24627
looks like you should call super
method in your overriden writer:
def recipient_list=(recipients) #jquery-token-input
self.recipient_ids = recipients.split(",")
super(recipients)
end
or something similar depends on your code.
Upvotes: 1