facebook_session.user.friends_with_this_app.map(&:id).join(","); how can I do such thing in Facebooker2 - facebooker2

<%= fb_multi_friend_selector("Invite your friends to check out this site", :showborder => true,:exclude_ids => facebook_session.user.friends_with_this_app.map(&:id).join(","), :condensed => false) %>
as you see above , :exclude_ids => facebook_session.user.friends_with_this_app.map(&:id).join(","), this line can remove the friends who had been a friends of you and joined in the app listed there. Recently, I upgraded to Facebooker2. how can I do the same thing in Facebooker2?
there is no function named friends_with_this_app in Facebookers and Mogli.

I haven't been able to figure out a one step solution to this. However you could do:
<% every_friend = current_facebook_user.friends.map(&:id) %>
# replace user with your class and fb_id with your user's facebook id field name
<% app_friends = User.where( :fb_id => every_friend ).map(&:id) %>
then your code
<%= fb_multi_friend_selector("Invite your friends to check out this site", :showborder => true,:exclude_ids => app_friends, :condensed => false) %>

Related

How to write nested axios post request in rails project?

I have been trying to convert the views of a project written initially in Ruby on Rails and I have pretty much succeeded in it. The next step is to write React APIs that will request and send data to the rails models. Here is where I am stuck.
So Initially I had to write the APIs for user registration, login and logout which I have succeeded in but now I need to write APIs for the nested resources and I am not able to solve the issue.
So the scenario in the application is that each user can have many projects and each project will have one project manager (from user model) and can have multiple developers and QAs (also from user table). The project manager of each project is being managed through a foreign key named "manager_id" in the projects table while the developers and QAs of the projects are being managed through a has_and_belongs_to_many association and hence through a join table as well.
My model of user and project is following
Project.rb:
class Project < ApplicationRecord
belongs_to :project_manager, class_name: 'User', foreign_key: :manager_id
has_and_belongs_to_many :users
end
User.rb:
class User < ApplicationRecord
has_many :projects_as_project_manager, class_name: 'Project', foreign_key: :manager_id
has_and_belongs_to_many :projects
end
After running through the rake routes command I get to see that the URI for projects#create is /users/:user_id/projects(.:format)
For project creation, I have created a form and on submit I am sending the post request in the following way
const saveProject = (e) => {
const API_URL = "http://localhost:3000/users/" + user_details.id + "/projects";
e.preventDefault();
const temp_project = {title: title, deadline: deadline, status: status, manager_id: user_details.id};
axios.post(API_URL, temp_project).then((promise) => {
console.log("Response in promise is: ", promise);
}).catch((error) => {
console.log("error in catch block is: ", error);
})
}
For clarification purposes let me state that project users(developers and qas) can be null as well so I am just sending manager id in addition to the project form field.
But I am getting the following error. Kindly help me out here
The code above is a javascript code. You should render Ruby variables in erb in order to view the ruby variables. for instance <%= user_details.id %> Check the code beneath.
If the source of the javascript code is in a js.erb file then you should make the variables ~> instance variables. i.e #user_details so that you can access them in the js file like this: <%= #user_details.id %>.
const saveProject = (e) => {
const API_URL = "http://localhost:3000/users/" + <%= user_details.id %> + "/projects";
e.preventDefault();
const temp_project = {title: <%= title %>, deadline: <%= deadline %>, status: <%= status %>, manager_id: <%= user_details.id %>};
axios.post(API_URL, temp_project).then((promise) => {
console.log("Response in promise is: ", promise);
}).catch((error) => {
console.log("error in catch block is: ", error);
})
}
Finally I was able to find out the mistake which infact was a really stupid one. I had not generated the controller for projects model and that's why I was getting the bad request error as the request being generated from axios was not being submitted anywhere.

CakePHP Clicking PDF Link and View it on New Tab

Ok, so I have a web app that uploads a file to the webserver. My input fields in my upload form include: type of upload (dropdown list), title, description, and the file to be uploaded, which is a PDF.
Once the PDF file is uploaded, the download link will appear in another page for the public to see. In addition, the title typed in the input field is the download link.
Now, I want to change my code. Instead of downloading it directly when the link is clicked I want it to open in a new tab, so the users can first look at the PDF file then download it from there.
Here are my codes.
Controller:
public function sendFile(){
$id = $this->request->params['pass'][0];
$staffup = $this->StaffUpload->find('first', array('conditions' => array('iduploads'=>$id)));
$this->response->file($staffup['StaffUpload']['dest'], array('download' => true, 'name' => $staffup['StaffUpload']['title']));
return $this->response;
}
The code above is the download function.
public function resources() {
$this->layout = 'website';
$this->set('staff_uploads', $this->StaffUpload->find('all', array('conditions' => array('type' => 'Resource'))));
}
The code above is the view wherein I show all uploaded files which type is Resources.
View:
<?php
foreach ($staff_uploads as $staff_uploads) {
?>
ul>
<li>
<?php
echo $this->Html->link($staff_uploads['StaffUpload']['title'], array('controller' => 'websites', 'action' => 'sendFile', $staff_uploads['StaffUpload']['iduploads']));
?>
</li>
</ul>
<?php
}
?>
The code above shows the view.
So yeah, back to the question. I want to change the download link to a link in which when clicked, will show the PDF file in a new tab. How do I do that? And by the way, the codes posted above are all working properly. I just want to change my code so that it will be viewed in a new tab when clicked.
Thank you!
According to the docs:
echo $this->Html->link(
'Enter',
'/pages/home',
array('target' => '_blank')
);

Deleting Multiple selected items from table

In my table I have a column with a check box for each row. I want to be able to delete all the selected items. I found the code from this website and modified it for my own stuff.
Link
I followed the website's naming convention for the check boxes and it is as follows:
<td> <?php echo $this->Form->checkbox('LocalClocks.id.['.$LocalClock['LocalClock']['id'].']', array('value' => $LocalClock['LocalClock']['id'])); ?></td>
This is the code in my controller for the deleteSelected() function:
public function deleteSelected()
{
foreach($this->data['LocalClocks'] as $key => $value)
{
if($value != 0)
{
$this->LocalClock->del($value);
}
}
$this->redirect($this->referer());
}
This is the code for the actual delete button (just in case it is needed):
<?php echo $this->Form->postLink('Delete Selected', array('action' => 'deleteSelected'), array('confirm' => 'Are you sure?')); ?>
There are a couple things I think might be the problem:
The code was written for an older version of cake, I think the website said 1.3, but I don't know what to update/correct in the existing code to make it work.
The delete button is the same as the one on cakephp's website on the blog tutorial. The only change I made was removing the id of the item to delete, because im not deleting a single item but multiple items.
Any help would be great.
Your checkbox input should be something like this
echo $this->Form->checkbox('LocalClocks.'.$LocalClock['LocalClock']['id'], array(
'value' => $LocalClock['LocalClock']['id'],
'hiddenField' => false
));
This will create a data array that will look like this
array(
'LocalClocks' => array(
1 => 1,
42 => 1
)
);
And will omit any unchecked ones from the data array because we're not using the hidden field. Finally, just a couple changes to your action
public function deleteSelected()
{
foreach($this->request->data['LocalClocks'] as $key => $value)
{
$this->LocalClock->delete($key);
}
$this->redirect($this->referer());
}
I prefer using Model::delete() to Model::deleteAll() because it runs the callbacks, where deleteAll does not.
Finally, your link will actually be a submit button. This will POST the data to the controller.
echo $this->Form->end('Submit');
If you want to use ajax, use the JsHelper to submit it instead. The following creates an Ajax submission that updates the dom element #mytable with the results of the action (in this case the referer that you redirect to).
echo $this->Js->submit('Submit', array(
'update' => '#mytable'
));
echo $this->Form->end();
once you got the list of your checked boxes; rather than using foreach loop to delete your ids one by one try this:
$this->Model->deleteAll(array('Model.column' => array($keys)));

Paperclip does not save attachment

I am new in Rails and web development...
I have created a User model, and I am now trying to give the user the ability to add a profile picture, using Paperclip.
From my user show page, a user can click on a link to open an 'edit' page, from which he can see a form to browse and choose an image to upload. When clicking on the button, it calls the 'update' action and redirect to the user show page, but the image is not saved in any folder, and the image attributes (filename, contenttype, filesize) are still set to NIL in the database.
I have installed and tested ImageMagick
I have added the :multipart => true in the form
I have put attr_accessible :avatar
I have set the paperclip options to look for '/usr/bin/' where convert is located
I have run the migration
I have set :url and :path
-in the controller, my update action is:
def update
#user = User.find(params[:id])
#title = "Update profile picture"
response_to do |format|
if #user.update_attributes(params[:user])
format.html {redirect_to(#user, :notice => 'Profile picture loaded')}
else
format.html {render :action => "edit", :notice => 'Unable to load pic")}
end
end
end
My model code is:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :number_of_positive_reco, :confidence_percent, :password,
:password_confirmation, :avatar, :avatar_file_name, :avatar_content_file, :avatar_file_size
has_attached_file :avatar , :styles => { :medium => "300x300>", :thumb => "100x100>"},
:url => "/images/profiles/:attachment/:id_:style.:extension",
:path => ":rails_root/public/images/profiles/:attachment/:id_:style.:extension"
# :default_url => "/images/Default_profile_picture.png"
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 20}
validates :email, :presence => true,
:format => { :with => email_regex},
:uniqueness => {:case_sensitive => false}
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
validates :number_of_positive_reco, :numericality => {:only_integer => true, :greater_than_or_equal_to => 0}
validates :confidence_percent, :numericality => { :greater_than_or_equal_to => 0.0, :less_than_or_equal_to => 1.0}
before_save :encrypt_password
# Return true if the user's password matches the submitted password.
def has_password?(submitted_password)
encrypted_password == encrypt(submitted_password)
end
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return nil if user.nil?
return user if user.has_password?(submitted_password)
end
def self.authenticate_with_salt(id, cookie_salt)
user = find_by_id(id)
(user && user.salt == cookie_salt) ? user : nil
end
private
def encrypt_password
self.salt = make_salt if new_record?
self.encrypted_password = encrypt(password)
end
def encrypt(string)
secure_hash("#{salt}--#{string}")
end
def make_salt
secure_hash("#{Time.now.utc}--#{password}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
end
The form is located in edit.html.erb:
<h1>
Ajouter une photo au profil
</h1>
<%= form_for #user, :html => { :multipart => true} do |f| %>
<div class="field">
<%= f.label :avatar, "Upload ta photo" %>
<br />
<%= f.file_field :avatar %>
</div>
<div class="actions">
<%= f.submit "Upload" %>
</div>
<% end %>
And I printed the debug information into the browser. After clicking Upload, I got this:
{"commit"=>"Upload", "authenticity_token"=>"+ExcuQOSv1bxIyAoM5+N4TCSmYI8JYeh5Yb8P5W4VU0=", "_method"=>"put", "utf8"=>"✓", "action"=>"update", "id"=>"8", "controller"=>"users", "user"=>{"avatar"=>#<ActionDispatch::Http::UploadedFile:0xb6d63fec #content_type="image/jpeg", #original_filename="Paperclip-Railway.jpg", #tempfile=#<File:/tmp/RackMultipart20111208-1681-3h3ps4-0>, #headers="Content-Disposition: form-data; name=\"user[avatar]\"; filename=\"Paperclip-Railway.jpg\"\r\nContent-Type: image/jpeg\r\n">}}
So, in the log, I see that the 'paperclip's fields' are filled with image name, image type, etc...but there is no "INSERT into TABLE", all the user fields are still NIL, the system directory where user's image should be stored is not created, there is no "Paperclip attachment save", nor any mention of paperclip in the log...
In console mode, I can create a new user, setting the avatar attributes as :
`User.create(:avatar => File.new(Rails.root + "public/images/an_image.png")´
and it works just fine! ... I also tested the creation of a new folder, without admin rights, and it works all fine ... I am desesperate :-(
Can anyone help me ?
3 days to find this out: as I used password protection (password being attr_accessor), it's impossible to update a user, without adding the password field in the form.
Trying to edit the profile picture without entering the password does not work, and no error message that could have me made me think about this was generated.
So, in the edit view, don't forget to add the password field in the form to be able to update user's picture!

Using HtmlHelper on Model to insert links in returned errors

I'm working with CakePHP and trying to understand the best ways to make my application consistent and logical.
Now I'm trying to working with Model data validation and handling validation errors in the view, I have a doubt on how should I do if I like to insert some link inside the returned error, for example for a forgotten password.
Is it good to use (if it's possibile) HtmlHelper inside the Model to return consistent links inside my application, or should I think about another way?
<?php
App::import('Helper', 'Html');
class User extends AppModel {
var $name = 'User';
var $validate = array (
'email' => array (
'checkEmail' => array (
'rule' => array('email', true),
'message' => 'Email not valid message.'
),
'checkUnique' => array (
'rule' => 'isUnique',
'message' => 'This email is allready in the db, if you forgot the password, '.(string)$this->Html->link('click here', array('controller' => 'users', 'action' => 'password-recover')).'.'
)
)
// the rest of the code...
This doesn't work because it seems I can't chain the message string with HTML string.
Does exist e smartest way to do that, or should I simply insert the html string without the HtmlHelper?
If you really want HTML in your validation messages CakePHP provides a way to do this, no breaking Cake, no writing a lot of code.
In your $validation just use whatever HTML you would like to have presented to the user.
In your view when you create your FormHelper::input($fieldName, array $options) pass the following array to $options:
$options = array('error' => array(
'attributes' => array('escape' => false)
))
See this page to learn more about the $options['error'] ...options.
Alternatively, if you want all inputs with no HTML escaping you can pass $options['inputDefaults'] when you create the form.
this is a difficult topic because
you might need to break MVC
validation is as in your case usually in $validate and cannot contain dynamic stuff
for 1)
you can also use Router::url() with manual HTML
you can use BBcode or pseudo-markup and translate this into real links in the view/element of the flashmessage
for 2)
use __construct() and $this->validate to use dynamic elements if needed
In PHP, properties of a class (such as $validate) have to be initialized with constant values.
<?php
class User extends AppModel {
public $validate = array(
'email' => array(
'checkUnique' => array(
'rule' => array('isUnique'),
'message' => 'This email address has already been claimed, possibly by you. If this is your email address, use the reset password facility to regain access to your account'
),
),
);
public function beforeValidate($options = array()) {
$this->validate['email']['checkUnique']['message'] = String::insert(
$this->validate['email']['checkUnique']['message'],
array('link' => Router::url(array('action' => 'password-recover')))
);
return true;
}
You are making it hard on yourself. The helpers are not accessible in the model and controller. And for good reason: the M and C shouldn't be concerned with the V.
There are ways to do exactly as you want (but involves considerably more code). Since you ask for the smartest way: What's wrong with just echo the reset password link in the view, after the login form? Just echo 'Forgot your password? '.$this->Html->link('Click here', array('controller' => 'users', 'action' => 'password-recover'));
I don't agree on breaking the MVC logic. I also tried all the array('escape' => false) possible ways (in Form->input, in Form->error and even in the model) and none of them worked with me! (cakephp 2.0)
"Anh Pham" answer is the easiest and simplest way. In addition to that, I returned empty error message from model validation ('errorMessage' => false ; doesn't work in cakePhp 2.0).
Because I wanted to pass a variable to the view to build the link there (MVC), in the controller I check if the field is invalidated:
$invlaidFields = array_keys($this->Model->validationErrors();
if ( in_array('myField', $invalidFields) ){
...
}
In the view, I check if the field was invalidated, I then echo my error message giving it class error-message so it looks the same as the rest error messages.
if ($this->Form->('myFields')) { ... echo '<span class="error-message">error message'. $this->Html->link(...).'</span>'; }
Hope it helps somebody out there.
P.S. It's always a good practice to mention what cakePHP version you are using...
To cakephp2 you can use the following:
//model validation
'company' => array('notempty' => array('rule' => array('notempty'),'message' => "select one company o send email to contact",),)
//front
<?php if ($this->Form->isFieldError('Register.company')): ?>
<span class="text-danger"><?php echo $this->Form->error('Register.company', null, array('escape'=>false)); ?></span>
<?php endif; ?>

Resources