Reputation: 197
I have two boolean fields in a table in my database.
both are defaulted to FALSE
This is what I have in my view
<%= label_tag(:post_draft, "Draft?") %>
<div class="ItemCheckboxAlign"><%= f.check_box :draft %></div>
As you can see, I have one of them working correctly. Is it possible to associate the other boolean field so if checked, the value changes to TRUE as well? I want to keep these two boolean field values completely separate from each other except I'm trying to update both with this one checkbox.
My schema:
create_table "posts", :force => true do |t|
t.text "content"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.boolean "draft", :default => false
t.boolean "sendreminder", :default => false
end
I'm trying to get the bottom two boolean fields changed to TRUE if the checkmark is checked when a user posts. I already have the "draft" working, but just trying to the other one to change as well at once.
After some discussion below, I am trying to apply the update_attribute(sendreminder, true)
method. How can I include this in my model to make sendreminder=true only if draft=true?
Upvotes: 0
Views: 197
Reputation: 9693
On the controller, you can do something like:
my_model = MyModel.find(params[:id])
my_model.assign_attributes(params[:my_model])
my_model.sendreminder = my_model.draft
if my_model.save
bla bla bla
else
bla bla bla
end
just make sure to replace MyModel with the model you are using, and the bla bla bla is pseudo code :)
If you want that to work the same for each time you save the model, you can use a before filter on your mode.
class Post < ActiveRecord:Base
before_save :associate_draft
def associate_draft
self.sendreminder = self.draft unless self.sendreminder == true
end
end
and then every time you save or update the model, that filter will be executed and the value of post_draft will be always the same value than draft.
Upvotes: 0
Reputation: 3205
You can also add a before_save
callback to your model and check whether you need to update other fields or not, based on the new state of the model instance.
Upvotes: 2