My question is this, I have my postgres database called gas_stations and only has a field called name, and I need that the form shows all the data in combobox from the table. also one of the options should appear "new station" and the truth I don't know how to do this
I think you tale about table and not database. To do this, you must to create a model called GasStation like this :
class GasStation < ActiveRecord::Base
end
After that, you could create a list in your view like this :
select("gas_station", "name", GasStation.all.collect {|gs| [ gs.name, gs.id ] }, { :include_blank => true })
See the guide here : http://guides.rubyonrails.org/getting_started.html.
select("form_name", "gas_station_id", GasStation.all.collect {|g| [ g.name, g.id ] }, { :include_blank => true })
Something like this should get you started. Of course you need to create the Model etc ...
If you don't know how, use a quick tutorial to learn rails basics!
Related
I have two questions:
In Rails 3 you can update multiple records using
Product.update(params[:products].keys, params[:products].values)
How do you do the same thing in Rails 4 using Strong Parameters? How about creating multiple records at the same time? Can you please elaborate your solution with an example in a format like the following:
params = ActionController::Parameters.new(...)
Product.create!(params.require(...)permit(...)
Also, my products model has a column called number which is equal to the order that they are updated. Is there a way to pass a counter value to the number while updating?
Thanks.
Solution w/o accepts_nested_attributes_for
This is my 2nd ever answer on SO, but I came across this problem multiple times, couldn't as of this writing find a reasonable solution and finally figured it out myself after doing a little nested_attributes hypothesizing and wanted to share my best understanding of it. I believe the strong params line you're after is this:
product_params = params.require(:products).permit(product_fields: [:value1, :value2, etc...])
I don't know exactly what your form looks like, but you will need to have a fields_for to nest the params in the product_fields(or any_name):
form_for :products do |f|
f.fields_for product_fields[] do |pf|
pf.select :value1
pf.select :value2
...
end
end
This will allow the permit() to accept a single explicit hash
product_fields => {0 => {value1: 'value', value2: 'value'}}
instead of the key/value pairs
0 => {value1: 'value', value2: 'value'}, 1 => {value1: 'value', value2: 'value'}, etc...
which you'd otherwise have to name individually:
.permit(0 => [value1: 'value', value2: 'value'], 1 => [...], 2 => [...], ad infinitum)
This allows you to update multiple products without having to use a parent model accepting nested attributes. I just tested this on my own project in Rails 4.2 and it worked like a charm. As for creating multiple: How would I save multiple records at once in Rails?.
As for a counter, you may need to iterate over each model individually:
product_params[:product_fields].keys.each_index do |index|
Product.create!(product_params.merge(counter: index))
end
Thought it's been so long you probably resolved that on your own. :-)
Maybe you're thinking about using nested_attributes?
That would look something like this:
params.require(:parent_model).permit(
:id,
child_models_attributes: [
:id,
:parent_model_id,
:child_model_attribute_1,
:child_model_attribute_2
]
)
with
params = {
id: parent_model.id,
child_models_attributes: {
'0' => {
id: child_model_1.id,
parent_model_id: parent_model.id,
child_model_attribute_1: 'value 1',
child_model_attribute_2: 12312
}
}
}
You would need to allow nested_attributes for the parent model like this though:
class ChildModel < Activerecord::Base
belongs_to :parent_model
end
class ParentModel < Activerecord::Base
has_many :child_models
accepts_nested_attributes_for :child_models
end
[I'm new to rails, and I hope it's not a silly question, seen a similar question but it's for PHP and doesn't help in my case]
To explain my problem, I'm using a analogy to users here. Lets say I have users table in my app, I have added a field called user_type to users table. Now I want to specify which type of user is.
lets say I have 5 types of users eg. moderator, administrator, consumer etc.
I don't want to make user_type field to be string type to store user type. Instead I want to make user_type to store integer and then map these integer values to respective string values.
Advantage to this approach is that I can change what a user type is called. Suppose that I no longer wish to call consumer a consumer and instead wish to call it something else.
I believe storing integer in db is better and gives some flexibility.
I know I can create select menu using formtastic(I'm using active_admin as admin panel, formtastic is used for forms)
<%= f.input :user_type, :as => :select, :collection => {
0 => "Admin",
1 => "Moderator",
2 => "Consumer",
} %>
and then store values in db, and then select these users from db.
I want to know Is there a better way or approach to do it in rails or there is some gem available to do this or some other approach you prefer and why you recommend it.
I'm using postgresql as database.
Thanks!!
I personally like the active_enum gem combined to simple_form because it's really simple to implement and they work fine together.
In your case, you would have to define an enum class like this :
class Type < ActiveEnum::Base
value 1 => 'Admin'
value 2 => 'Moderator'
value 3 => 'Consumer'
end
Then in your User model, you simply add this :
enumerate :user_type, :with => Type
And what is really great with simple_form is that you simply have to call :
<%= f.input :user_type =>
to get a select with all your values.
Try this
# user.rb
USER_TYPES = { moderator: 1, superuser: 2, admin: 3, client: 4 }
# views
select :user, :user_type, User::USER_TYPES
This saves the integer values to the database. If you want to get the the string equivalent, use User::USER_TYPES.key(#user.user_type)
EDIT: forgot to add scopes
scope :moderators, where(user_type: USER_TYPES[:moderator])
scope :superusers, where(user_type: USER_TYPES[:superuser])
...
or
USER_TYPES.each do |user_type, value|
scope :"#{user_type}s", where(user_type: USER_TYPES[user_type])
end
I am doing something like this to insert multiple records at the same time in my rails app.
VoteRecord.create(
[
{ :prospect_id => prospect.id, :state => "OH", :election_type => "GE" },
{ :prospect_id => prospect.id, :state => "OH", :election_type => "PR" }
...
]
)
When I check the log i see that the insert query is fired multiple times by sql. Is it possible to do this in a single query?
You can try active record import for bulk import,checkout wiki and example page.
I haven't used it myself, but you should check out the activerecord-import project (for Rails 3)
github More on this can be found here: wiki
I'm trying to create a form that has:
TextInput--Skill
DropDown--Years Experience
Using jQuery, I have the input and drop down fields populate if a user has more skills to add. Is it possible to store many sets of skills and their respective years experience in a database entry?
I've been looking into has_many:
Thank you!
No need for extra query here (has_many), look into rails serialization:
class User < ActiveRecord::Base
serialize :preferences, Hash
end
user = User.create(:preferences => { "background" => "black", "display" => "large" })
User.find(user.id).preferences # => { "background" => "black", "display" => "large" }
You can do the same with Array
I'm relatively new to Mongoid/MongoDB and I have a question about how to model a specific many-to-many relationship.
I have a User model and a Project model. Users can belong to many projects, and each project membership includes one role (eg. "administrator", "editor", or "viewer"). If I were using ActiveRecord then I'd set up a many-to-many association between User and Project using has_many :through and then I'd put a field for role in the join table.
What is a good way to model this scenario in MongoDB and how would I declare that model with Mongoid? The example below seems like a good way to model this, but I don't know how to elegantly declare the relational association between User and the embedded ProjectMembership with Mongoid.
Thanks in advance!
db.projects.insert(
{
"name" : "Test project",
"memberships" : [
{
"user_id" : ObjectId("4d730fcfcedc351d67000002"),
"role" : "administrator"
},
{
"role" : "editor",
"user_id" : ObjectId("4d731fe3cedc351fa7000002")
}
]
}
)
db.projects.ensureIndex({"memberships.user_id": 1})
Modeling a good Mongodb schema really depends on how you access your data. In your described case, you will index your memberships.user_id key which seems ok. But your document size will grow as you will add viewers, editors and administrators. Also, your schema will make it difficult to make querys like:
Query projects, where user_id xxx is editor:
Again, you maybe do not need to query projects like this, so your schema looks fine. But if you need to query your projects by user_id AND role, i would recommend you creating a 'project_membership' collection :
db.project_memberships.insert(
{
"project_id" : ObjectId("4d730fcfcedc351d67000032"),
"editors" : [
ObjectId("4d730fcfcedc351d67000002"),
ObjectId("4d730fcfcedc351d67000004")
],
"viewers" : [
ObjectId("4d730fcfcedc351d67000002"),
ObjectId("4d730fcfcedc351d67000004"),
ObjectId("4d730fcfcedc351d67000001"),
ObjectId("4d730fcfcedc351d67000005")
],
"administrator" : [
ObjectId("4d730fcfcedc351d67000011"),
ObjectId("4d730fcfcedc351d67000012")
]
}
)
db.project_memberships.ensureIndex({"editors": 1})
db.project_memberships.ensureIndex({"viewers": 1})
db.project_memberships.ensureIndex({"administrator": 1})
Or even easier... add an index on your project schema:
db.projects.ensureIndex({"memberships.role": 1})