rails 3, 2 check_boxes shouldn't be false at the same time, how? - ruby

I have a form like this:
<div class="row">
<div class="span6 offset3">
<%= form_for #user do |f| %>
<%= render '/shared/error_messages' %>
<%= f.label :name %>
<%= f.text_field :name %>
........
<% if current_user.admin? %>
<%= f.label :admin %>
<%= f.check_box :admin, {checked: true} %>
<br /><br />
<%= f.label :developer %>
<%= f.check_box :developer %>
<% end %>
........
<%= f.submit "Invite new user", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
As you see, there are two check_boxs to determine whether the new user admin or developer. Admin is checked by default.
What I want to do is, when somebody click checked admin, it won't be unchecked. When click developer, admin will be unchecked and developer will be checked.
New user must be either admin or developer. Both check_boxes should never false at the same time

This functionality (only one possible choice) is for radio button, not checkbox

use radio buttons. If you still insist on using checkboxes, give both the check boxes a class name, bind the class in a javascript with live and do the validation !
$('.checkboxes').live('change', function(){
if($(this).is(':checked')){
dosomething...
}
});

Related

First radio_button not showing in Rails 5

I'm using Devise within Rails 5 and have added Enum/roles (Consumer, Designer) to the User model. When creating a new registration, I want the user to select a role, for which I've added a radio_button for each value/role:
<div id="user_role"
<% User.roles.keys.each do |role| %>
<%= f.radio_button :role, role %>
<%= f.label role.to_sym %>
<% end %>
</div>
It's showing the labels of both roles, but only the radio_button for the last role. Here are the roles defined in the User model:
enum role: [:consumer, :designer]
Any ideas on what I'm doing wrong here?
try to this way
<div id="user_role">
<% User.roles.keys.each do |role| %>
<%= f.radio_button :role, role %>
<%= f.label role.to_sym %>
<% end %>
</div>
or
<div id="user_role">
<% User.roles.each do |role| %>
<%= f.radio_button :role, role %>
<%= f.label role[0] %>
<% end %>
</div>
it's working fine in my local.I hope it's will be help you.

add form (non-nested) dynamically in rails

pls can someone explain how I can dynamically add another copy of a form in rails?...been working on this for almost 2hrs. I messed around with .clone() and .appendTo in jquery, but it didnt work. Also, most of the materials I found online (like on railscast #196 and stackoverflow) focused heavily on nested forms. My form is nested, but I actually just want to add the parent form again. The photos which are nested use the html multiple attributes so I'm guessing that will handle multiple files upload for each parent form (btw I'm using paperclip).
If I just need to modify the railscast code please let me know.
Thanks.
<%= form_for(#user_book, html: { multipart: true }) do |f| %>
<% if #user_book.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#user_book.errors.count, "error") %> prohibited this user_book from been saved:</h2>
<ul>
<% #user_book.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<p>hello</p>
<% end %>
</ul>
</div>
<% end %>
<%= f.text_field :title, placeholder: "enter title...", id: "book_title" %>
<%= f.text_field :category, placeholder: "enter category..." %>
<%= file_field_tag 'user_book[user_book_photos_attributes][][photo]', :multiple => true do |p| %>
<%= p.file_field :photo %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>

RoR: How can I get my microposts to show up?

Here is the users show view where they are supposed to show up. ..
<section>
<div id= "purchases">
<%= render 'shared/micropost_form_purchase' %>
</div>
<div id="sales">
<%= render 'shared/micropost_form_sale' %>
</div>
</section>
<%= #sales %> <%# This is just to see if it outputs anything. It doesn't :( %>
<div id="purchases list">
<ol class="microposts">
<%= render #purchases unless #purchases.nil? %>
</ol>
</div>
<div id="sales list">
<ol class="microposts">
<%= render #sales unless #sales.nil? %>
</ol>
</div>
so the forms (partials) are loading fine, but then when I make a post, in either one, neither the purchases list nor the sales list shows up. I checked the database and they are being created along with an entry in the column indicating kind (either sale or purchase).
Here are the forms:
<%= form_for (#micropost) do |f| %>
<div class="field no-indent">
<%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
<%= hidden_field_tag 'micropost[kind]', "purchase" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
and
<%= form_for (#micropost) do |f| %>
<div class="field no-indent">
<%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
<%= hidden_field_tag 'micropost[kind]', "sale" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
also, here is the show part of the users_controller.rb
def show
#user = User.find(params[:id])
#micropost=Micropost.new
#microposts = #user.microposts.paginate(page: params[:page])
end
and here is the show part of the microposts_controller.rb
def show
#micropost = Micropost.find(params[:id])
#microposts = Micropost.where(:user_id => #user.id)
#purchases= #microposts.collect{ |m| m if m.kind == "purchase"}.compact
#sales = #microposts.collect{ |m| m if m.kind == "sale"}.compact
end
additionally, with the help of this post (http://stackoverflow.com/questions/12505845/ruby-error-wrong-number-of-arguments-0-for-1#12505865) the variables #microposts, #purchases, and #sales are all outputting correctly in the console.
can anyone help me out?
edit: using scopes as suggested by the answer given works in the console (it outputs everything correctly, but they still don't show up in the view. Does this mean it is something wrong with my syntax for the users show page?
edit 2:
Here is the view/microposts/_micropost.html.erb code
<li>
<span class="content"><%= micropost.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(micropost.created_at) %> ago.
</span>
<% if current_user?(micropost.user) %>
<%= link_to "delete", micropost, method: :delete,
confirm: "You sure?",
title: micropost.content %>
<% end %>
</li>
I'm making some assumptions without seeing more of your code, but it looks like you could
write what you've shown a little differently. I'm assuming your databases are migrating
and have the required columns, e.g., Micropost#kind, Micropost#user_id, etc.
You can use scopes to refine a collection of microposts more expressively. It might be helpful to read
up about ActiveRecord scopes: http://guides.rubyonrails.org/active_record_querying.html#scopes.
class Micropost < ActiveRecord::Base
belongs_to :user
scope :purchases, where(:kind => "purchase")
scope :sales, where(:kind => "sale")
# your code
end
I'm also assuming your user has many microposts:
class User < ActiveRecord::Base
has_many :microposts
# your code
end
For your forms, I'd suggest attaching your hidden field to the form object (f.hidden_field) so
you don't have to specify the name as 'micropost[kind]'.
<%= form_for(#micropost) do |f| %>
<div class="field no-indent">
<%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
<%= f.hidden_field :kind, :value => "sale" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
In MicropostsController#show, you can use your new scopes:
def show
#micropost = Micropost.find(params[:id])
#microposts = #user.microposts
#purchases = #microposts.purchases
#sales = #microposts.sales
end
You should also confirm that your MicropostsController#create action is actually adding
the microposts to the user sending the form (I'm assuming a current user method).
def create
#micropost = current_user.microposts.create(params[:micropost])
# yada
end
You can also confirm expected results on rails console after creating purchases or sales micropost with:
Micropost.purchases
Micropost.sales
Again, I could be missing something without seeing more of the code base.
Check Micropost.count, #purchases.count, #sales.count (by printing them in the controller, or some part of the view) to see if the records actually exist.
Also, if you want to render collections likes #sales and #purchases, you need to make sure that the model partial exists (_micropost.html.erb in your case). That is probably where you need to look for the view errors. For all you know, that file could be empty, thus no errors will show up at all.
The problem might also lie in your microposts#create (or whichever action that you are saving the micropost in), the micropost should be associated with the current_user:
#micropost = current_user.microposts.build(params[:micropost])
Taking this and your previous question into account, I suggest you go through the original code for the RoR tutorial again (and verify that all tests are passing) before taking it apart. You can always add new tests to it for your experiments and they will help in figuring out where you went wrong.

How do I add form errors for a model that belongs to another model, rails 3.1

I'm following along with the Rails Guides - Getting Started tutorial. It makes a basic Post model, and a Comment model that belongs to Post.
I have added a simple validation to the Comment model, and it works, but I can't figure out how to get form errors to display if I fill it out wrong.
Here is my comment.rb model
class Comment < ActiveRecord::Base
validates :body, presence: true
belongs_to :post
end
Here is the original form for adding a comment, it's in posts/show.html.erb
<h2>Add a comment:</h2>
<%= form_for([#post, #post.comments.build]) do |f| %>
<div class="field">
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
</div>
<div class="field">
<%= f.label :body %><br />
<%= f.text_area :body %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And the original create action in comments_controller.rb
class CommentsController < ApplicationController
def create
#post = Post.find(params[:post_id])
#comment = #post.comments.create(params[:comment])
redirect_to post_path(#post)
end
end
I've tried quite a few things, but it all feels like fumbling around in the dark. Can someone point me in the right direction please?
Take a look at the dynamic_form gem - this used to be part of Rail itself but was extracted a while back. With it, you can display errors inline like this:
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
<%= f.error_message_on :commenter %>

Rails 3 Render / Partial

I'm very new to Rails 3 and I've followed some tutorials and now I'm trying to "play" with the code created. I have followed the tutorial from http://guides.rubyonrails.org/getting_started.html
I'm am trying to render the form for new posts on the homepage with this code:
<%= render :partial => "posts/form" %>
The posts/_form.html.erb looks like this:
<%= form_for(#post) do |f| %>
<% if #post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
and this is the error I get:
undefined method `model_name' for NilClass:Class
Extracted source (around line #1):
1: <%= form_for(#post) do |f| %>
2: <% if #post.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(#post.errors.count, "error") %> prohibited this post from being saved:</h2>
Trace of template inclusion: app/views/home/index.html.erb
Rails.root: d:/server/cazare
Application Trace | Framework Trace | Full Trace
app/views/posts/_form.html.erb:1:in `_app_views_posts__form_html_erb___794893824_70478136_519766'
app/views/home/index.html.erb:5:in `_app_views_home_index_html_erb__967672939_70487520_0'
I understand that this may seem a piece of cake for some of you but I'm trying to understand how everything works on Rails so I hope you can understand me.
Thanks in advance !
#post variable is not instantiated in the Controller :)
so "#post = Post.new" inside the controller action should do the trick
Rails is attempting to build a form for the object #post. In order to do that, it needs to know what sort of object #post is; that way, it can find any existing data in the object and fill it into the form for you. Rails has a method grafted on to objects called model_name to do the lookup, but it won't be grafted onto NilClass (the class of the nil object).
I suspect that you haven't defined #post anywhere - it's an instance variable of the Controller, so you'd expect the controller to either find #post from the database, or to call #post = Post.new - so it's nil.
In the posts/_form.html.erb,
change
<%= form_for(#post) do |f| %>
to
<%= form_for(Post.new) do |f| %>

Resources