In Rails 3.2 , how do you create multiple records on tick of a check box ?
In my view I use as
= check_box_tag 'product[product_ids][]', product.id
I checked the development logs and the checkbox values are as
"product"=>{"product_ids"=>["193", "195"]}
And in the controller I do something as
#cpr = CouponProductRestriction.new(params[:product])
#cpr.save
But I get an error as
Can't mass-assign protected attributes: product_ids
Is there something I am doing wrong ?
The error message indicates it is not the problem of the checkbox. You just need to add an attr_accessible declaration. In other words add the following line in the Product model:
attr_accessible :product_ids
Related
Okey i just dont understand what can be wrong here
i have this app where users are approved by and admin and this was working fine until a few days ago
in my view i have a link that calls my user controller
<%= link_to 'Approve', active_user_path(user), :method => :put %>
here is my custum route for that link
match "users/:id/activate" => "users#activate", :as => "active_user"
now in my user controller i have this activate method
def activate
#user = User.find(params[:id])
puts #user.name #the correct name is displayed
puts #user.is_approved.inspect.to_i #:is_approved is 0
if #user.update_attribute(:is_approved, 1)
puts #user.is_approved.inspect # :is_approved is 1
#user.activate_user
puts #user.is_approved.inspect # :is_approved is 1
#user.save!
redirect_to "/users?is_approved=0"
else
render "/" # dosn't matter
end
end
I try to save 3 times here (update, activate_user, save!) but still the value will not be saved, the users is_approved field is still 0, how is that possible ?
here is my model method
def activate_user
self.is_approved = 1
self.save
end
btw i can update strings with this method but not integers (true and false dosnt work either)
in my model i have is_approved as both attr_accessible and attr_accessor
The solution
Well this is awkward but so it happens that in my user model i had attr_accessor :approved this resulted in that the model never went to the database to update the :approved column BUT instead it updated the local variable :approved so next time when i looked at the column then of course the :approved value had not changed
tldr?
if you have attr_accessor in your model with the same name as the column your trying to update => remove it
Never use attr_accessor on an attribute which is backed by a database column - the accessor generated by attr_accessor will mask the value stored in the database
update_attribute actually does more than just updating a single column:
Validation is skipped.
Callbacks are invoked.
updated_at/updated_on column is updated if that column is available.
Updates all the attributes that are dirty in this object.
Are there any callbacks in your User model?
Make sure the column is not being updated somewhere in a callback.
I am new to Rails. Please help. I have 2 fields in model
class Article < ActiveRecord::Base
attr_accessible :title, :url, :description
end
After user enters the title, we need to auto populate the url form field by changing the following in title
remove all special characters from title
replace spaces with dash "-"
downcase
Then user can update the url to customize it further. Finally, when he clicks on "Create Article" button, we need to check the above 3 conditions again to validate.
I am using Rails 3.2.6
Thank you.
I assume that its a web app and the user is give a form with two textboxes where he can enter the title and url.
You can use javascript to auto generate the url in the textbox, where user can customize it and save.
I'm trying to use activeadmin's batch_action so I can run actions on more than one record. However when trying to run my rails server I get the following error.
undefined method `batch_action' for #<ActiveAdmin::ResourceDSL:0xb11f980> (NoMethodError)
Here is the activeadmin resource code:
ActiveAdmin.register Product do
batch_action :destroy, false
filter :name
index do
selectable_column
column :name
default_actions
end
controller do
def current_company
#current_company
end
end
end
I'm not sure where I'm getting it wrong - I need to show a corresponding checkboxes against the records and then define a batch action. Where am I getting it wrong here?
Got the answer :) was a wrong entry in my gemfile.
https://github.com/gregbell/active_admin/issues/1302
I have two model classes, Patient and Prescription, with a belongs_to relationship:
class Prescription
belongs_to :patient
...
I have a form for creating new Prescription objects, and I want it to get the patient from a hidden field:
<%= form_for(#prescription) do |f| %>
...
<%= f.hidden_field :patient_id, :value => #patient.id %>
...
In the prescriptions controller I want to create a new prescription using the params I got from the form:
def create
#prescription = Prescription.new(params[:prescription])
...
Something is not working. I can see in the log that the patient id is being passed in the params, but it is not getting inserted into the db:
Started POST "/prescriptions" for 127.0.0.1 at 2011-05-13 14:59:00 +0200
Processing by PrescriptionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"h3rizbBoW069EfvQf6NyzH53k+g4o4XO61jeZ/GF6t0=", "prescription"=>{"medicine_name"=>"w", "dispense_date(1i)"=>"2011", "dispense_date(2i)"=>"5", "dispense_date(3i)"=>"13", "days_supply"=>"2", "patient_id"=>"1"}, "commit"=>"Create Prescription"}
WARNING: Can't mass-assign protected attributes: patient_id
Patient Load (0.2ms) SELECT "patients".* FROM "patients" WHERE "patients"."id" IS NULL LIMIT 1
AREL (0.4ms) INSERT INTO "prescriptions" ("medicine_name", "dispense_date", "days_supply", "patient_id", "created_at", "updated_at") VALUES ('w', '2011-05-13', 2, NULL, '2011-05-13 12:59:00.690434', '2011-05-13 12:59:00.690434')
What does the warning message about mass-assign protected attributes mean? How do I change the code so it works?
I think you have missed one of the great things about rails which would really help in this scenario. And that is the possibility to nest resources in the routing.
For example, if your routes.rb looks like this:
resources :patients do
resources :prescriptions
end
That would result in the url for your controller looking like /patients/:patient_id/prescriptions/ and the result of that is that since the patient_id is already existing in the url, you don't have to have any hidden form to store it. So in your PrescriptionsController, the create action could look like this:
def create
#patient = Patient.find(params[:patient_id])
#prescription = #patient.prescriptions.build(params[:prescription])
When you use the association to "build" the instance instead of directly with the model, it will automatically assign the patient_id for you.
This may not be the exact answer to your question but this is probably the way I would have done it.
'Cannot mass-assign' means you cannot assign a value automatically like this:
# In the examples below #prescription.patient_id will not be set/updated
#prescription = Prescription.new(params[:prescription])
#prescription.update_attributes(params[:prescription])
You can solve this by setting :patient_id as attr_accessible in your Prescription model. If you do this make sure you understand the security risks.
attr_accessible :patient_id
Or by assigning a value to patient_id directly:
#prescription.patient_id = some_value
I didn't put enough in my code snippets, above. It turns out the problem was due to this in my model:
class Prescription:
belongs_to :patient
attr_accessible :medicine_name, :dispense_date, :days_supply
So I didn't have patient on the list of attr_accessible, and this caused the error message. I don't really understand what the attr_accessible is needed for, and everything worked if I removed it.
Thankyou for your comments, especially the one about the nested resources, I will look into that.
I'd like to slugify the urls for a model in Rails 3, using Mongoid. The problem is the fields I want to use in the slug are located in a child model. I am using mongoid-slug gem to find a solution to this and my attempt so far is this:
class Building
references_one :address
def to_param
address.to_param
end
end
class Address
referenced_in :building
field :houseno
field :street
slug :houseno, :street
end
While this allows me to form the correct url by calling building_path(building), the page does not contain the correct values. Error message complains that object id is incorrect, and I'm not sure how to get Rails to listen and find the record by to_param.
For the curious, here is how I solved my own problem. I realized that I needed to use change the show action from
#building = Building.find(params[:id])
to
#building = Address.find_by_slug(params[:id]).building
And voila! It works.