How do I make a settings configuration page for the rails-settings gem? - ruby-on-rails-3

I just discovered the rails-settings gem and now I need to make an admin page that lets me edit the setting values. How would I make a settings controller with an edit view that can change these dynamic app wide settings?

I haven't used this gem but it seems like it should be fairly straight forward. Since it uses a database backed model, you would simply create a controller as normal:
rails g controller Settings
From here you would define your index action to gather all your individual settings for display in the view:
def index
#settings = Settings.all
end
Then in the view you can setup a loop to display them:
<% #settings.each do |setting| %>
<%= setting.var %> = <%= setting.value %>
<% end %>
As far as editing ... this might be a bit tricky since by default rails would expect you to submit only one setting at a time to edit. You could do it this way but unless you implement the edit with ajax it might be tedious and non-intuitive.
Another way would be to set up your update method to accept all the individual settings at once, loop through and update each one with new values. It might look something like this:
// The /settings route would need to be setup manually since it is without an id (the default)
<%= form_tag("/settings", :method => "put") do %>
<% #settings.each do |setting| %>
<%= label_tag(setting.var, setting.var) %>
<%= text_field_tag(setting.var, :value => setting.value) %>
<% end %>
<%= submit_tag("Save Changes") %>
<% end %>
This should output all of the settings (given they have been assigned to the #settings variable) with the var name as the label and the current value as the text field value. Assuming that the routing is setup, when you submit this form the action that receives it should all the new settings in the params variable. Then you can do something like this in the action:
def update
params.each_pair do |setting, value|
eval("Settings.#{setting} = #{value}")
end
redirect_to settings_path, :notice => 'Settings updated' # Redirect to the settings index
end
This may not be the best way depending on how often you edit the settings and how many settings you have...but this is a possible solution.

I was looking for some suggestions for this and found another answer to this that is very simple and elegant, for anyone looking for this later. It just sets up dynamic accessors in your model, allowing your form to have settings fields just like your normal attributes. An example can be found in the original answer:
How to create a form for the rails-settings plugin

Related

Rails sessions stored in database

I have a page that shows a list of events. When the event is clicked it takes you to a login page and it keeps the session id along with the page. When I go to the next page it always sends the last session variable.
<% #events.each do |e| %>
<%= link_to e.event_name, sessions_new_path %>
<%= e.event_start %> - <%= e.event_stop %>
<% session[:event_id] = e.id %>
<%= session[:event_id] %>
<br>
<% end %>
This shows the session[:event_id] is there and it is storing in the variable but when I click on the link it will send the last session[:event_id] of the loop. Any ideas would be helpful. I am looking at option of either passing the variable to the next page or storing it into a database cell, but not sure on how sessions are stored in databases.
Assuming you are using a supported database with ActiveRecord, you can configure your application to store sessions in the database by editing your_app/config/initializers/session_store.rb:
YourApp::Application.config.session_store :active_record_store
make sure to comment out or remove the line:
# YourApp::Application.config.session_store :cookie_store, :key => '_your_app_session'
Further, there are auth gems that handle redirecting users to protected pages after signing in. If you haven't already, look at Devise and/or authlogic. Personally, I prefer Devise.

Editing multiple records at once - how to update without IDs

Still new to Rails. I'll try to provide as much detail as possible.
I have a form that lets me update multiple records at one time.
It's based off the 'Editing Multiple Individually' Railscast episode.
<%= form_tag(auction_clerk_path(#auction), :method => :put) do %>
<% #lots.each do |lot| %>
<%= fields_for "lots[]", lot do |f| %>
<%= f.number_field :sale_price %>
<% end %>
<% end %>
<% end %>
(Simplified to just include a single input for each instance)
An Auction contains multiple Lots (items for sale).
The auction_clerk_path is the route I'm using to just show all lots on one auction.
Everything is working just fine... until I use try to customize my lot paths...
I've added the following to my lot.rb file to be able to use:
/auctions/:auction_id/lots/:lot_number
instead of /auctions/:auction_id/lots/:id
def to_param
lot_number
end
So, in the form mentioned earlier, the fields render with name="lots[12][sale_price]" where 12 is the id.
However with the to_param change, now the fields render with name="lots[1][sale_price]" where 1 is the lot_number.
When I save, the submitted parameters are lot_numbers instead of ids.
So obviously when it tries to update, it won't find the correct records.
My method definition looks like this:
def save_clerking
#updated_lots = Lot.update(params[:lots].keys, params[:lots].values).reject { |l| l.errors.empty? }
if #updated_lots.empty?
flash[:notice] = "Lots updated"
redirect_to auction_clerk_path(#auction)
else
render :action => "clerk"
end
end
I either need to change my method definition to lookup by lot number, or change the form to somehow output IDs in the first place... but I don't know how.
Any help is appreciated. Thanks!
Fixed this through some help on another question.
I changed my method def to
#updated_lots = []
params[:lots].each do |lot_number, attributes|
lot = Lot.where("lot_number = ? AND auction_id = ?", lot_number, params[:auction_id]).first
if lot.update_attributes(attributes)
#updated_lots << lot
end
end
You could fetch the ids by lot number in the controller action and feed those to the update method instead of the params keys.

Rails ERB -- get the generated HTML content to a variable I can access in a controller

I am doing an online contract agreement which is generated dynamically based on the current state of our contract language (stored in an ERB partial).
When the user clicks "I Agree" we save the variable data, but I also want to store the contents of the rendered partial (html fragment) in the database.
I tried using ActionView::Helpers::CaptureHelper.capture -- wrapping the whole partial in a block and rendering at the end, like
<% #saved_output = capture do %>
...
The rest of the erb with instance variable <%= #my_class.name %> and so on
...
<% end %>
<%= #saved_output %>
<% logger.debug "Rendered output is: #{#saved_output}" %>
And this produced the same result and also sent the correct text to the log. But it appears to go out of scope -- even if I declare #saved_output = nil prior to render it's nil when I end the block.
I tried using content_for as well ... which makes some sense to me, but ... huh, just not getting it. Any helpful pointers appreciated.
Have you tried render_to_string in your controller when you're creating the record? That may allow you to just go ahead and "snapshot" the page.

Correct way to share a view in the index page

I'm a Ruby-on-Rails newbie, just starting out.
I have an MVC called "account_types", generated via scaffold to produce:
controllers/account_types_controller.rb
helpers/account_types_helper.rb
models/account_type.rb
views/account_types/_form, edit, index etc...
Going to localhost:3000/account_types gives me the index view.
What I'd like to do is display the same data as selected from the account_types index method in the application index page as a list.
I wrote a new view called account_types/_list.html_erb as follows:
<ul>
<% #account_types.each do |account| %>
<li><% account.label %></li>
<% end %>
</ul>
I then edited home/index.html.erb (This is based on examples given in other questions on SO):
<%= render :partial => 'account_types/list', :module_types => #module_types %>
However I get
undefined method `each' for nil:NilClass
and the error displays the code from account_types/_list.html.erb where I've written
<% #account_types.each do |account| %>
The scaffolded views work fine, why aren't mine?
Are partials the right thing to use here?
Thanks in advance.
What is the correct way to define an application-wide partial and its variables in rails says to use a before_filter on ApplicationController.
You pass :module_types to partial, but use account_types. As I can see you just need to change your index.html.erb to:
<%= render :partial => 'account_types/list', :account_types => #module_types %>
You can use partials for this if you want, though it would be unnecessary in this case as far as I can tell (they are for sharing chunks of code between several views). In order to get this code to work you'll need to define #account_types in your controller with something like
#account_types = AccountType.all
You can see exact line in your account_types_controller.rb under index action. :module_types => #module_types is not necessary here, since I doubt you defined #module_types either and you don't use module_types in your partial at all.
It's obvious, that you don't understand how Rails works, so I suggest reading through a good tutorial (like this one) before you proceed with whatever you have in mind.

Merging the List, Show, New and Edit actions of Rails

I am new in Rails.
I want a Simple Example in Rails 3 with only one index.html.erb file with All Actions merged including New, listing, Show , Edit (e.g all Actions) and If Example with Relationship of 1-to-Many will be perfect for me.
Take Example as Purchase Order(PO_Num, Date) has many Products(Name, Qty, Price)
Why do you want to merge the templates for all of the actions into one template? They're all conceptually quite different views, so having separate templates is normally a good idea. If you have shared code between them, there are better ways of achieving this (eg using partials or helpers).
If you really want to override a template used in an action, you can just call the render method:
def show
render "index"
end
You can check for action_name in the view:
<% case action_name %>
<% when 'index' %>
... view part for index action here
<% when 'show' %>
... view part for show action here
<% when 'new' %>
... view part for new action here
<% when 'edit' %>
... view part for edit action here
<% end %>